Execute SQL command in Entity Framework Core 2.0 to delete all data in a table
Ensure that you reference Microsoft.EntityFrameworkCore
to include all the necessary extension methods that would allow you to execute raw SQL commands.
From the source repository I found ExecuteSqlCommand
and related extension methods
int count = await context.Database.ExecuteSqlCommandAsync("DELETE FROM [Blogs]");
Found an article that suggested using ADO.Net.
First you grab a connection from the context, create a command and execute that.
using (var connection = context.Database.GetDbConnection()) {
await connection.OpenAsync();
using (var command = connection.CreateCommand()) {
command.CommandText = "DELETE FROM [Blogs]";
var result = await command.ExecuteNonQueryAsync();
}
}
This will perform over any of delete row-per-row from table methods.
context.ExecuteStoreCommand("TRUNCATE TABLE [" + tableName + "]");
TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources.
ExecuteStoreCommand
TRUNCATE TABLE
For EF Core 3.x, use this namespace and this code :
using Microsoft.EntityFrameworkCore;
...
context.Database.ExecuteSqlRaw("TRUNCATE TABLE [TableName]");