Apply all migrations up to specific migration

.net-core c# entity-framework-core

Question

It is possible to apply all migrations by using the RelationalDatabaseFacadeExtensions.Migrate extension method. e.g.

if (_ctx.Database.GetPendingMigrations().Any())
{
    //Apply migration
    _ctx.Database.Migrate();
}

However, I have a specific requirement to carry out the following migration actions at runtime:

  1. Apply migrations up to a certain point
  2. Seed some data
  3. Apply all remaining migrations (this will remove columns which are no longer required after the seeding)

Is there a method that I can use to apply all migrations up to a specific (named) migration at runtime (e.g. an equivalent to the .net Core CLI command dotnet ef database update)?

1
2
7/23/2018 7:04:37 PM

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