如何从 ObjectContext 中删除属于 EntityObjects 集合的 EntityObject?
我想对我的 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.
I would like to perform a delete on my ObjectContext
.
This is my code:
var tempList = someEntityObject.SomeCollectionOfEntityObject;
foreach (var item in tempList)
{
someObjectContext.DeleteObject(item);
tempList.Remove(item);
}
I want to delete someEntityObject
, but before i can, i need to delete all objects in SomeCollectionOfEntityObject
. I have a foreign key constraint that prevents me from deleting someEntityObject
.
When the foreach tries to loop the second time i get this error:
System.InvalidOperationException occurred
Message=Collection was modified; enumeration operation may not execute.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以先将集合填充到某个真正的临时列表,而不是在 tempList 上使用 foreach。
然后清除 tempList,然后可以迭代 realList。
Instead of using foreach on tempList you can populate the collections to some real temporary list first.
Then you clear tempList and then you can iterate over realList.
使用 while 循环代替:
Use a while loop instead:
另一种选择是在关系上指定级联删除。
这将导致在删除 someEntityObject 时自动删除 SomeCollectionOfEntityObject 中的所有记录。
请注意,您必须在模型和数据库上执行此操作,才能使其可靠地工作。有关详细信息,请参阅此帖子:http://blogs.msdn.com/b/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx。
Another option is to specify cascade delete on the relationship.
This will cause all of the records in SomeCollectionOfEntityObject to be deleted automatically when you delete someEntityObject.
Note that you must do this on both the model and the database for it to work reliably. See this post for more information: http://blogs.msdn.com/b/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx.