Entity Framework. Delete all rows in table

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

Edit:

Currently in net6.0 (dotnet 6 core) you can do the following:

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

Or use the Async overload:

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

These are extension methods coming from Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions

If you’re having issues with foreign keys (in MySql), you might have to do the following (Doing the SET FOREIGN_KEY_CHECKS = 0; part in a separate call does not seem to work for me)

context.Database.ExecuteSqlRaw("SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE [TableName];");

So if you want to truncate your entire database (Possibly for unittesting reasons) – you can do the following:

var tableNames = context.Model.GetEntityTypes()
    .Select(t => t.GetTableName())
    .Distinct()
    .ToList();

foreach (var tableName in tableNames)
{
    context.Database.ExecuteSqlRaw($"SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE `{tableName}`;");
}

Leave a Comment