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
var data = (from n in db.users select n);
db.users.RemoveRange(data);
db.SaveChanges();
dataDb.Table.RemoveRange(dataDb.Table);
dataDb.SaveChanges();
This avoids using any sql
using (var context = new MyDbContext())
{
var itemsToDelete = context.Set<MyTable>();
context.MyTables.RemoveRange(itemsToDelete);
context.SaveChanges();
}
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]");
var all = from c in dataDb.Table select c;
dataDb.Table.RemoveRange(all);
dataDb.SaveChanges();
Make sure when you are trying to delete parent all children will cascade on delete. Or children have nullable foreign key.