Entity Framework. Delete all rows in table

前端 未结 21 1772
一生所求
一生所求 2020-11-28 01:25

How I can quickly remove all rows in table using Entity Framework?

I am currently using:

var rows = from o in dataDb.Table
           select o;
forea         


        
相关标签:
21条回答
  • 2020-11-28 02:02
    var data = (from n in db.users select n);
    db.users.RemoveRange(data);
    db.SaveChanges();
    
    0 讨论(0)
  • 2020-11-28 02:03
    dataDb.Table.RemoveRange(dataDb.Table);
    dataDb.SaveChanges();
    
    0 讨论(0)
  • 2020-11-28 02:04

    This avoids using any sql

    using (var context = new MyDbContext())
    {
        var itemsToDelete = context.Set<MyTable>();
        context.MyTables.RemoveRange(itemsToDelete);
        context.SaveChanges();
    }
    
    0 讨论(0)
  • 2020-11-28 02:05

    Using SQL's TRUNCATE TABLE command will be the fastest as it operates on the table and not on individual rows.

    dataDb.ExecuteStoreCommand("TRUNCATE TABLE [Table]");
    

    Assuming dataDb is a DbContext (not an ObjectContext), you can wrap it and use the method like this:

    var objCtx = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)dataDb).ObjectContext;
    objCtx.ExecuteStoreCommand("TRUNCATE TABLE [Table]");
    
    0 讨论(0)
  • 2020-11-28 02:05
    var all = from c in dataDb.Table select c;
    dataDb.Table.RemoveRange(all);
    dataDb.SaveChanges();
    
    0 讨论(0)
  • 2020-11-28 02:07

    Make sure when you are trying to delete parent all children will cascade on delete. Or children have nullable foreign key.

    0 讨论(0)
提交回复
热议问题