DeleteObject() in foreach loop

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 ?

Answers


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));

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));

Need Your Help

High-precision clock in Python

python time

Is there a way to measure time with high-precision in Python --- more precise than one second? I doubt that there is a cross-platform way of doing that; I'm interesting in high precision time on U...

Ruby on Rails 3 - Reload lib directory for each request

ruby-on-rails reload rails-engines ruby-on-rails-3

I'm creating a new engine for a rails 3 application. As you can guess, this engine is in the lib directory of my application.