How to Quickly Delete All Rows in a Table in Entity Framework?

There are times when you would be required to delete all the records from the table using Entity Framework. One of the commonly used approach is to iterate each rows and use the DBSet.Table.Remove as shown below.

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

How to Quickly Delete All Rows in a Table in Entity Framework?

The Other quickest simple option to delete all the rows in a table in entity framework is to use the TRUNCATE table query and execute it with the ExecuteSqlCommand as shown below.

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

Note : If you want to use the DDL command, you would need to have the ALTER permission on the table.

%d