Skip to main content
 首页 » 编程设计

c#之如何从 ObjectContext 中删除属于 EntityObjects 集合的 EntityObject

2024年02月02日27lonelyxmas

我想对我的 ObjectContext 执行删除操作。

这是我的代码:

var tempList = someEntityObject.SomeCollectionOfEntityObject; 
 
foreach (var item in tempList) 
{ 
    someObjectContext.DeleteObject(item); 
    tempList.Remove(item); 
} 

我想删除 someEntityObject,但在此之前,我需要删除 SomeCollectionOfEntityObject 中的所有对象。我有一个外键约束,阻止我删除 someEntityObject。

当 foreach 第二次尝试循环时,出现此错误:

System.InvalidOperationException occurred 
  Message=Collection was modified; enumeration operation may not execute. 

请您参考如下方法:

除了在 tempList 上使用 foreach 之外,您还可以先将集合填充到某个真正的临时列表中。

var realList = tempList.ToList(); 

然后清除 tempList,然后迭代 realList。