简体   繁体   中英

'Collection was modified' error when Deleting Related Entities

I am trying to delete some items using Entity Framework. I want to delete those items with DestinationId that is not in int[] destinationIds . (I am deleting rows in a junction table.)

foreach (var destination in product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId)))
    product.ImportedProductDestinations.Remove(destination);

But the foreach statement gives me the run-time error:

Collection was modified; enumeration operation may not execute.

Alright, I think I understand this error. But how else can I do what I'm trying to do?

do not remove the item from the collection you are scanning, delete it from the db context

context.IMportedProductDestinations.DeleteObject(destination);

and then apply the changes to the db using context.SaveChanges

You are getting the exception because, You are trying to iterate a collection using foreach and deleting an item from it. You can add ToList to your product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId)) and then remove the item.

foreach (var destination in product.ImportedProductDestinations
                                   .Where(ipd => !destinationIds.Contains(ipd.DestinationId))
                                   .ToList())
{
    product.ImportedProductDestinations.Remove(destination);
}

You cannot remove an item from a collection as you are iterating over it in a foreach.

var result = product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId)).ToList());

    For(int i= 0;i<result.count();i++)
    (
       product.ImportedProductDestinations.Remove(result[i]);
    )

Create a remove list:

 foreach (var destination in product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId)))
     ListRemove.Add(ipd.DestinationId)

foreach (var remove in  ListRemove)
product.ImportedProductDestinations.Remove(remove)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM