简体   繁体   English

删除相关实体时“收集已修改”错误

[英]'Collection was modified' error when Deleting Related Entities

I am trying to delete some items using Entity Framework. 我试图使用Entity Framework删除一些项目。 I want to delete those items with DestinationId that is not in int[] destinationIds . 我想删除那些不在int[] destinationIds DestinationId项目。 (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: 但是foreach语句给出了运行时错误:

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 不要从正在扫描的集合中删除该项目,将其从db上下文中删除

context.IMportedProductDestinations.DeleteObject(destination);

and then apply the changes to the db using context.SaveChanges 然后使用context.SaveChanges将更改应用于db

You are getting the exception because, You are trying to iterate a collection using foreach and deleting an item from it. 您将获得异常,因为您正在尝试使用foreach迭代集合并从中删除项目。 You can add ToList to your product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId)) and then remove the item. 您可以将ToList添加到您的product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId))然后删除该项目。

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. 当你在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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