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);
}
}
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).
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With