Entity Framework: Deleting a Request for Multiple Objects

I have a list that contains the PK identifier for several objects in the collection that I want to delete. Does anyone know how to write a single query to retrieve these objects?

For example:

IList<int> objectList; // populated with int Primary key Ids

using (MyEntities context = new MyEntities()){

    var result = context.MyObjectCollection.Where(obj=> obj.ID IN objectList);

    foreach(var item in result){
        context.DeletObject(item);
    }
    context.SaveChanges();
}

Any help would be greatly appreciated!

+3
source share
3 answers
var result = context.MyObjectCollection.Where(obj=> objectList.Contains(obj.ID));
+1
source

Mel's answer does not work because in .NET 3.5 SP1 EF does not know how to translate list.Contains (...) in T-SQL. Although this happens in 4.0.

The workaround is to manually create a large OR query, i.e.

Where(obj => obj.ID == item1 || obj.ID == item2 ....)

Here is the tip I wrote that makes this easy:

Tip 8 - How to Write Where IN Style Queries Using LINQ to Entities

Hope this helps

Entity Framework - Entity Framework

+1

http://efe.codeplex.com

this.Devices.Update(o => new Device() { LastOrderRequest = DateTime.Now, Description = "teste" }, o => o.Id == 1);
0
source

Source: https://habr.com/ru/post/1715165/


All Articles