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 ?
Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable.
The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove . Therefore, the for-each loop is not usable for filtering.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With