Entity Framework Core 2.0 - Run migrations step by step

ef-migrations entity-framework entity-framework-core

Question

In EF6 I could retrieve migrations and run it step by step.
Is there a way to do something similar in EF Core?

EF 6 Code

public static void RunMigration(this DbContext context, DbMigration migration, string providerName, string manifest)
{
    var prop = migration.GetType().GetProperty("Operations", BindingFlags.NonPublic | BindingFlags.Instance);
    if (prop != null)
    {
        IEnumerable<MigrationOperation> operations = prop.GetValue(migration) as IEnumerable<MigrationOperation>;
        MigrationSqlGenerator generator = (new DbMigrationsConfiguration()).GetSqlGenerator(providerName);
        var statements = generator.Generate(operations, manifest);
        foreach (MigrationStatement item in statements)
            context.Database.ExecuteSqlCommand(item.Sql);
    }
}
1
5
8/20/2017 9:31:18 AM

Accepted Answer

You can use the GetPendingMigrations extension method of the DatabaseFacade class (returned by Database property of the DbContext) to get the list of the pending migration names.

Then you can obtain IMigrator service and use Migrate method passing each target migration name:

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

DbContext db = ...;
var pendingMigrations = db.Database.GetPendingMigrations().ToList();
if (pendingMigrations.Any())
{
    var migrator = db.Database.GetService<IMigrator>();
    foreach (var targetMigration in pendingMigrations)
        migrator.Migrate(targetMigration);
}
8
3/11/2020 7:31:37 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow