Skip to content
Advertisement

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

I want to execute an SQL command from Entity Framework Core 2.0, but I can’t figure out how to do so.

1.- The reason why I need to, is that I want to delete all data from a database table, and using Context.remove or Context.removeRange would produce many calls to DB (one for each data in the table).

2.- I’ve read that there is a method .ExecuteSqlCommand to accomplish that, but that method is not present in my Context.Database (maybe in Core 2.0 it was removed?). Here is the source of the info: Dropping table In Entity Framework Core and UWP

So, basically I need to delete a table from code using EF Core 2.0 and, as far as I know, I need to execute a SQL command for that.

Thank you.

Here is my .csproj, just in case i’m missing something

Advertisement

Answer

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

Found an article that suggested using ADO.Net.

First you grab a connection from the context, create a command and execute that.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement