我想对我的 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。
