This is a really straightforward activity.
Using EF Core code-first approach in .NET Core applications we always tend add migrations as our application entities change.
Do we really need to always run the update-database
command. I think not.
put this code snippet anywhere you find comfortable in ur project
private async Task RunMigration<T>(T db) where T : DbContext
{
List<string> pendingMigrations = db.Database.GetPendingMigrations().ToList();
if (pendingMigrations.Any())
{
IMigrator migrator = db.Database.GetService<IMigrator>();
foreach (string targetMigration in pendingMigrations)
{
migrator.Migrate(targetMigration);
}
}
await Task.CompletedTask;
}
Also, say you have multiple contexts, notice how the snippet above uses generic type to handle any context that inherits DbContext.
The last step will be to add RunMigration(yourDbContext)
to your Startup.Configure
method.
Have fun!!
Top comments (0)