如何从实体框架集合中删除项目子集
我有一个实体框架EntityCollection
。
我需要从数据库中删除与给定 where 子句匹配的所有项目。这是我现有的代码:
// Perform the deletes
foreach (var deleteReq in order.Requirements.Where(x=>!orderContract.Requirements.Any(y=>y.RequirementId==x.RequirementId)))
{
order.Requirements.Remove(deleteReq);
}
基本上,我试图从 order.Requirements 集合中删除不在 orderContract.Requirements 集合中的任何内容(与 Id 匹配)。
正如您可能猜到的,此代码会抛出异常,因为我正在修改正在迭代的集合。
通常我只会使用 RemoveAll()
但 EntityCollection
不支持该方法。
那么...我怎样才能删除我需要的所有记录呢?
I have an entity framework EntityCollection
.
I need to delete all items that match a given where clause from the database. This is my existing code:
// Perform the deletes
foreach (var deleteReq in order.Requirements.Where(x=>!orderContract.Requirements.Any(y=>y.RequirementId==x.RequirementId)))
{
order.Requirements.Remove(deleteReq);
}
Basically I am trying to remove anything from the order.Requirements collection that is not in the orderContract.Requirements collection (matching on an Id).
As you may guess, this code throws and exception because I am modifying the collection I am iterating.
Normally I would just use RemoveAll()
but the EntityCollection
does not support that method.
So... How can I delete all the records I need to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我创建了一个单独的列表,它似乎有效:
这样,当我从 order.Requirements 列表中删除该项目时,它不会影响我正在迭代的列表。
I created a seperate list and it seems to have worked:
That way, when I remove the item from the order.Requirements list, it is not affecting the list that I am iterating.
将要删除的所有需求实体收集到列表中。
然后从需求实体集合中而不是从 order.Requirements 中删除其中的每一项。
collect all the Requirement entities you want to delete into a list.
Then remove each one of those from the Requirements entity collection rather than from order.Requirements.
在 EF6 之前,有一个
RemoveRange
方法可以提供更好的性能和更干净的 API现在,EF 不会在删除之前加载每个项目,因为这是已接受答案中的情况。
Prior to EF6, there is a
RemoveRange
method for better performance and cleaner APINow, the EF wont load each item before remove, as it is a case in the accepted answer.