如何使用 Code-First EF 4.1 从数据库中删除多个项目
我们使用带有 DbContext 和 DbSet<> 的代码优先 EF 4以及带有 DataAnnotations 的 POCO。 我对此很陌生,似乎无法找到问题的答案:
如何直接从数据库中删除多个项目,而不先使用 LINQ 选择项目,然后执行循环并调用 Remove(item)
每次迭代?这对我来说似乎很愚蠢。
与此相关的所有引用都引用了似乎不存在的函数,例如我的 DbContext 中不存在的 DeleteOnSubmit(item)
。此外,它仅删除一项。
有更好的办法吗?
We use code-first EF 4 with DbContext and DbSet<> and POCOs with DataAnnotations.
I am new to this and cannot seem to find an answer to my quesiton:
How can I delete multiple items from the DB directly without first selecting the items with LINQ and then doing loop and call Remove(item)
on each iteration? That seems silly to me.
All references concerning this refer to function that don't seem to exist, like DeleteOnSubmit(item)
which isn't there in my DbContext. Also, it only deletes ONE item.
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DeleteOnSubmit
是来自DataContext
类的函数 = Linq-to-SQL在删除项目之前不必加载它。如果你知道它的密钥就足够了。像这样的东西应该可以工作:
或者
如果不指定要删除的每个单个项目,则无法使用 EF 删除多个项目(级联删除除外)。如果你想直接删除多个项目,你必须使用 SQL 像
DeleteOnSubmit
is function fromDataContext
class = Linq-to-SQLYo don't have to load item before you delete it. It is enough if you know its key. Something like this should work:
or
There is no way to delete multiple items with EF (except cascade delete) without specifying each single item to be deleted. If you want to deleted multiple items directly you must use SQL like
实体框架不支持一次多次删除,因为它需要内存中的对象。您需要遍历循环。
Entity framework doesn't support multiple deletion at once as it required object in memory. You need to iterate through loop.