Reputation:
I have a List which hold the PK ID's of a number of objects in a collection that I want to remove. Does anyone know how to write a single query to retrieve these objects?
Eg:
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 greatly be appreciated!
Upvotes: 3
Views: 4268
Reputation: 1
this.Devices.Update(o => new Device() { LastOrderRequest = DateTime.Now, Description = "teste" }, o => o.Id == 1);
Upvotes: 0
Reputation: 20924
Mel's answer doesn't work because in .NET 3.5 SP1 the EF doesn't know how to translate list.Contains(...) into T-SQL. Although this is coming in 4.0.
The workaround is to manually produce a big OR query i.e.
Where(obj => obj.ID == item1 || obj.ID == item2 ....)
Here is a tip I wrote that makes that easy:
Tip 8 - How to write where IN style queries using LINQ to Entities
Hope this helps
Alex James
Entity Framework Team - Read my Entity Framework Tips
Upvotes: 1
Reputation: 2252
var result = context.MyObjectCollection.Where(obj=> objectList.Contains(obj.ID));
Upvotes: 1