使用实体框架删除大量项目 [英] Delete a big list of items with Entity Framework

查看:36
本文介绍了使用实体框架删除大量项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 EF 删除一大堆项目,所以我试图一个一个地删除它们,但需要很长时间.

I want to delete a big list of items with EF, so I tried to remove them one by one but it take long time.

我尝试在我的列表中使用 .RemoveAll() 方法,但它不更新数据库[仅从加载的实体中删除]

And I tried to use .RemoveAll() method with my list but it don't update the database [only remove from loaded entity]

所以我使用 SqlCommand 将它们从数据库中删除,并使用 .RemoveAll() 来防止 EF 意外的行数更新 (0) 异常.

So I use a SqlCommand to remove them from the database and I use .RemoveAll() to prevent EF unexpected number of rows update (0) exception.

代码:

dbContext.Database.ExecuteSqlCommand("DELETE FROM xxx WHERE xxx");
loadedEntity.subItems.ToList().RemoveAll(r => true);
dbContext.SaveChanges();

我的问题:有没有更好的方法来做到这一点?

My question: is there a better way to do this?

推荐答案

试试这个

var all = dbContext.XXX.Where(x => x.xxx == "xxx");
dbContext.XXX.RemoveRange(all);
dbContext.SaveChanges(); 

这篇关于使用实体框架删除大量项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆