开发者

DeleteObject() in foreach loop

开发者 https://www.devze.com 2023-01-06 15:57 出处:网络
With Entity Framewor开发者_开发百科k, I try to delete some objects from my object context like that :

With Entity Framewor开发者_开发百科k, 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 ?


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

精彩评论

暂无评论...
验证码 换一张
取 消