[英]Efficient way to delete multiple rows with Linq to Entity?
Hi I'm looking for efficient way to delete multiple records at once. 嗨,我正在寻找一次删除多个记录的有效方法。 I'm deleting 400 records and it takes 8-15 seconds.
我正在删除400条记录,需要8-15秒。 Here is my code
这是我的代码
using (var entities = new Entity())
{
foreach (Item item in entities.Items.Where(x => x.id == id))
entities.DeleteObject(item);
entities.SaveChanges();
}
You can do it faster using EntityFramework.Extensions 您可以使用EntityFramework.Extensions更快地完成此操作
1) First install EntityFramework.Extensions using NuGet 1)首先使用NuGet安装EntityFramework.Extensions
2) Here is the code similar to Linq2Sql's DeleteAllOnSubmit(): 2)这是类似于Linq2Sql的DeleteAllOnSubmit()的代码:
using EntityFramework.Extensions;
.... ....
using (var entities = new Entity())
{
entities.Items.Delete(x => x.id == id);
entities.SaveChanges();
}
...
In your loop: 在你的循环中:
using (var entities = new Entity())
{
foreach (Item item in entities.Items.Where(x => x.id == id))
entities.DeleteObject(item);
entities.SaveChanges();
}
If you move the entities.SaveChanges(); 如果你移动entities.SaveChanges(); so that it runs after the loop, it will run substantially faster.
因此它在循环之后运行,它将以更快的速度运行。
using (var entities = new Entity())
{
foreach (Item item in entities.Items.Where(x => x.id == id))
entities.DeleteObject(item);
}
entities.SaveChanges();
Check out Bulk-deleting in LINQ to Entities or PLINQO for Entity Framework if it's the sort of delete you could do in a single batch, ie 检查LINQ to Entities或PLINQO for Entity Framework中的 批量删除,如果它是您可以在一个批次中执行的那种删除,即
DELETE FROM Entities WHERE [some condition]
Otherwise, maybe check you've got an index on the x
column you're using to find each record. 否则,可能会检查您在用于查找每条记录的
x
列上是否有索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.