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


This content was proof-read by Grammarly. You can Try Grammary for FREE

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.


Are you a .NET Developer planning to integrate GraphQL for .NET in your Application? Check out this book
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 bloggers like this: