在Entity Framework中快速删除表中所有数据的一种方法
kelvin 发布于 2021-03-12

有时需要使用实体框架从表中删除所有记录。一种常用的方法是迭代每一行并使用DBSet.Table.Remove如下所示。

 var records = from m in customerDB.Customers
select m;
foreach (var record in records)
{
customerDB.Customers.Remove(record);
}
customerDB.SaveChanges();

然而上面这种方式速度太慢,在实体框架中删除表中所有行的另一个最快速的简单选项是使用TRUNCATE table查询并使用executesql命令执行它,如下所示。

 dbContext.Database.ExecuteSqlCommand("TRUNCATE TABLE Customer");


kelvin
关注 私信
文章
92
关注
0
粉丝
0