[英]“Collection was modified; enumeration operation may not execute” error when deleting
[英]'Collection was modified' error when Deleting Related Entities
我试图使用Entity Framework删除一些项目。 我想删除那些不在int[] destinationIds
DestinationId
项目。 (我正在删除联结表中的行。)
foreach (var destination in product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId)))
product.ImportedProductDestinations.Remove(destination);
但是foreach
语句给出了运行时错误:
收集被修改; 枚举操作可能无法执行。
好吧,我想我理解这个错误。 但我怎么能做我想做的事呢?
不要从正在扫描的集合中删除该项目,将其从db上下文中删除
context.IMportedProductDestinations.DeleteObject(destination);
然后使用context.SaveChanges将更改应用于db
您将获得异常,因为您正在尝试使用foreach
迭代集合并从中删除项目。 您可以将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);
}
当你在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]);
)
创建删除列表:
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.