Entity Framework Core 2.0 – Run migrations step by step

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);
}

Leave a Comment