In the foreach loop, use DeleteObject().

.net c# database entity-framework

Question

I attempt to remove certain items from my object context using Entity Framework in the following manner:

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

I get a "Collection Was Modified" Exception with this code.

Therefore, how can I batch delete?

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

Accepted Answer

Get the things you wish to remove from the collection you're going to change first. A simple LINQ query may do this (using ToList() to compel execution):

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

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

Alternatively, you might use: if you like concise syntax (I don't in this instance).

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

Popular Answer

When the Collection is changed in a foreach, you receive the exception.

Copying your collection is a solution.

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