我应该怎样删除一个DbSet所有元素?元素、DbSet

2023-09-02 10:43:42 作者:快意满斟

什么是删除一个System.Data.Entity.DbSet的所有元素,与实体框架4.3?

最好的方法 解决方案

  dbContext.Database.ExecuteSqlCommand(删除的MyTable);
 

(别开玩笑。)

问题是,EF不支持任何批处理命令,并使用没有直接的DML会删除一组的所有实体的唯一方法:

 的foreach(在dbContext.MyEntities VAR实体)
    dbContext.MyEntities.Remove(实体);
dbContext.SaveChanges();
 

或许豆蔻便宜一点,以避免加载完整的实体:

 的foreach(在dbContext.MyEntities.Select(E =&GT VAR ID; e.Id))
{
    VAR实体=新myEntity所{n = ID};
    dbContext.MyEntities.Attach(实体);
    dbContext.MyEntities.Remove(实体);
}
dbContext.SaveChanges();
 
JQuery,如何清除,除了点击的元素以外,其他所有元素

但在这两种情况下,你必须加载所有的实体或所有键属性,并通过一个来自集删除实体之一。此外,当你调用的SaveChanges EF将发送N(=实体的集合号)DELETE语句,这也得到了DB逐条执行数据库(在一个单一的交易)。

所以,直接的SQL显然是preferable为了这个目的,你只需要一个DELETE语句。

What's the best way to remove all elements in a System.Data.Entity.DbSet, with Entity Framework 4.3?

解决方案

dbContext.Database.ExecuteSqlCommand("delete from MyTable");

(No kidding.)

The problem is that EF doesn't support any batch commands and the only way to delete all entities in a set using no direct DML would be:

foreach (var entity in dbContext.MyEntities)
    dbContext.MyEntities.Remove(entity);
dbContext.SaveChanges();

Or maybe a litte bit cheaper to avoid loading full entities:

foreach (var id in dbContext.MyEntities.Select(e => e.Id))
{
    var entity = new MyEntity { Id = id };
    dbContext.MyEntities.Attach(entity);
    dbContext.MyEntities.Remove(entity);
}
dbContext.SaveChanges();

But in both cases you have to load all entities or all key properties and remove the entities one by one from the set. Moreover when you call SaveChanges EF will send n (=number of entities in the set) DELETE statements to the database which also get executed one by one in the DB (in a single transaction).

So, direct SQL is clearly preferable for this purpose as you only need a single DELETE statement.