In the foreach loop, use DeleteObject().

.net c# database entity-framework

Question

With Entity Framework, I try to delete some objects from my object context like that :

foreach (var item in context.Items.Where( i => i.Value > 50 ) )
{
   context.Items.DeleteObject(item);
}

With this code, I have a "Collection Was Modified" Exception.

So, how can I do a batch delete ?

1
18
7/8/2015 9:31:39 PM

Accepted Answer

You have to first get the items you want to delete out of the collection that you're going to modify. You can do this with a simple LINQ query (using ToList() to force execution):

var toDelete = context.Items.Where(i => i.Value > 50).ToList();

foreach(var item in toDelete)
{
    context.Items.DeleteObject(item);
}

Or if you like compact syntax (I don't, in this case), you could use:

context.Items
    .Where(i => i.Value > 50)
    .ToList()
    .ForEach(item => context.Items.DeleteObject(item));
28
7/8/2010 2:32:52 PM

Popular Answer

In a foreach, when the Collection is modified, you get the exception.

Solution: Copy your collection.

context.Items.Where( i => i.Value > 50 ).ToList().ForEach(item => context.Items.Remove(item));


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow