Search code examples
c#.net-coreentity-framework-migrationsentity-framework-core-2.1entity-framework-core-migrations

How to uninstall EF Core tables? Or how to remove all migrations ? Or how to call `dotnet ef database update 0` from user code?


I'm developing web app and near it small command line application that install ef core tables in the DB. Last can be done calling dbContext.Database.Migrate(); and this works.

Now I want to provide unistall option (with this app).

But how to remove migrations (means call functionality of dotnet ef database update 0 from my code) ?

It could be not one command call (as it was in case with dbContext.Database.Migrate();). But snippet with loop through all migrations in migrations assembly and call of 'Downs'.


Solution

  • EF Core provides publicly only the dbContext.Database.Migrate(); extension method used to migrate the latest version. It's mentioned in the Applying migrations at runtime section of the EF Core documentation, which also contains the following

    Note

    This method builds on top of the IMigrator service, which can be used for more advanced scenarios. Use DbContext.GetService<IMigrator>() to access it.

    which gives you the solution, because IMigrator interface provides Migrate method accepting optional targetMigration parameter with the same semantics as the dotnet ef database update or Update-Database PM commands. Passing "0" (which is the value of the Migration.InitialDatabase constant) will perform the operation in question.

    You'll need the following additional usings:

    using Microsoft.EntityFrameworkCore.Infrastructure;
    using Microsoft.EntityFrameworkCore.Migrations;
    

    and code like this:

    var migrator = dbContext.GetService<IMigrator>();
    migrator.Migrate(Migration.InitialDatabase);