Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework. Delete all rows in table

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

I am currently using:

var rows = from o in dataDb.Table            select o; foreach (var row in rows) {     dataDb.Table.Remove(row); } dataDb.SaveChanges(); 

However, it takes a long time to execute.

Are there any alternatives?

like image 292
Zhenia Avatar asked Mar 05 '13 09:03

Zhenia


People also ask

How do I remove all records from a table in Entity Framework?

Table select o; foreach (var row in rows) { dataDb. Table. Remove(row); } dataDb. SaveChanges();

How do I delete a row in Entity Framework?

In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.

How do I truncate a table in EF core?

Truncating a table is a data layer operation, not an object operation. The equivalent in Entity Framework would be to load all objects from the database and delete them one by one. You don't want that, you want to truncate the table. Then dive down into SQL and truncate that table.


1 Answers

For those that are googling this and ended up here like me, this is how you currently do it in EF5 and EF6:

context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]"); 

Assuming context is a System.Data.Entity.DbContext

like image 82
Ron Sijm Avatar answered Sep 25 '22 06:09

Ron Sijm