Execute SQL command in Entity Framework Core 2.0 to delete all data in a table

倾然丶 夕夏残阳落幕 提交于 2019-12-04 22:51:38

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

Context.Database.ExecuteSqlCommand and Context.Database.ExecuteSqlCommandAsync are available in Microsoft.EntityFrameworkCore.Relational namespace. Make sure you have it's reference.

Then it will be available in your class and you can call it like below,

Context.ExecuteSqlCommand("TRUNCATE TABLE YOURTABLENAME");

You can try this

 context.Patients.ToList().ForEach(v => v.ChangeTracker.State = ObjectState.Deleted);
 context.SaveChanges();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!