views:

48

answers:

2

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 ?

+5  A: 

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));
Justin Niessner
Very clever. I was just writing a similar answer but you were first.
Jeroen
+1  A: 

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(context.Items.DeleteObject(item));
cRichter
Clever. Even less code than the first answer.
Jeroen
You would get a +1 from me, but you need to fix your syntax.
Justin Niessner
ah, sorry for that @Justin. we have some extension in house, like that all collections get that foreach extension. And that is called Each().and BTW, if you so much operations in one line, please do not forget the documentation of it!
cRichter