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