Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core 2.0 - Run migrations step by step

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);
    }
}
like image 929
bubi Avatar asked Aug 20 '17 09:08

bubi


People also ask

How do you run migrations?

Open the Package Manager Console from Tools → Library Package Manager → Package Manager Console and then run the enable-migrations command (make sure that the default project is the project where your context class is).


Video Answer


1 Answers

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);
}
like image 64
Ivan Stoev Avatar answered Oct 23 '22 02:10

Ivan Stoev