Home > database >  EF Migrations - Delete Database schema before migration
EF Migrations - Delete Database schema before migration

Time:04-09

I am trying to create a migration, that would purge data for the whole schema and then run migrations. I have found a way to run the migrations for the context set only. I cannot find a way to delete the data in the given context, and not in the whole database.

Current code for migrations only:

var context = scope.ServiceProvider.GetRequiredService<TContext>();
await context.Database.MigrateAsync();

context.Database.EnsureDeleted(); has allowed me to delete the database before running migrations, but it seems to ignore the context I provide (as it says in the documentation).

Any ideas on how to delete data in the context?

Thanks!

CodePudding user response:

What I would suggest is to create an empty migration, then add the raw SQL in order to drop the schema:

  public partial class DropSchemaMigration : Migration
            {
                protected override void Up(MigrationBuilder migrationBuilder)
                {
                    migrationBuilder.Sql("DROP SCHEMA MY_SCHEMA;");
                }
        
        }

Then do your other migrations. Assuming that this is a code-first approach. You can stash all your changes, do the empty migration, pop stash and generate other migrations.

Or, if it feels more natural, do your migration, and on the first line in the Up method you can set the SQL command

public partial class MyMigration: Migration
            {
                protected override void Up(MigrationBuilder migrationBuilder)
                {
                    migrationBuilder.Sql("DROP SCHEMA MY_SCHEMA;");
                   //auto-generated mappings
                }
        
            }
  • Related