Automatically execute migrations when publishing ASP.NET Core app

So I added the option -environment to my ef database command. Now it works:

"postpublish": ["dnx ef database update -e Staging"]

I have four different appsettings.json which different connection string for each environment. Just needed to indicate the environment for the command to work.


In you Startup.cs class add this code

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetService<AppDBContext>(); 
            context.Database.Migrate(); 
        }
    }

Use context.Database.Migrate()

You can call this from your Startup class:

using (var context = new MyContext(...))
{
    context.Database.Migrate();
}

It will migrate your database to the latest version on application startup. But be careful doing it, maybe comment out this code and uncommend only when you want to run your migrations.


Apparently this process does not work now. https://github.com/aspnet/Home/issues/622 After you publish you should find the power shell script with the name of "profile name"-publish.ps1. Then add your commands below these three lines close to the end of this file. You might want to use powershell to make it easier to debug.

'Calling Publish-AspNet' | Write-Verbose

# call Publish-AspNet to perform the publish operation

Publish-AspNet -publishProperties $publishProperties -packOutput $packOutput