use entity framework to drop all tables. in csharp

To drop all tables in Entity Framework Core, you can use the following code:

main.cs
using Microsoft.EntityFrameworkCore;

public void DropAllTables(DbContext context)
{
    context.Database.ExecuteSqlCommand(@"
        DECLARE @sql NVARCHAR(MAX) = N'';

        SELECT @sql += N'DROP TABLE [' + s.name + N'].[' + t.name + N'];'
        FROM sys.tables AS t
        INNER JOIN sys.schemas AS s 
        ON t.[schema_id] = s.[schema_id];

        EXEC sp_executesql @sql;
    ");
}
396 chars
16 lines

This method uses raw SQL to query for all tables in the database and generates a DROP TABLE statement for each table. Then it executes the generated SQL using sp_executesql.

You can call this method passing an instance of your context:

main.cs
using (var context = new YourDbContext())
{
    DropAllTables(context);
}
74 chars
5 lines

Note that this is not recommended in production environments, as it will permanently delete all data in the database.

gistlibby LogSnag