How to run a migration in production

Updated with sample for 3.0

The Core 3.0 approach is similar to 2.x, but now the generic host is used. You will need to add using Microsoft.Extensions.DependencyInjection; for the CreateScope()

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var db = scope.ServiceProvider.GetService<ShortenerContext>();
        db.Database.Migrate();
    }

    host.Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Updated with better way for Core 2.0+

Migrations should be run in Program.cs due to tooling like the EF Core CLI tools running the Startup functions in normal execution.

Here is an example:

public class Program
{
  public static void Main(string[] args)
  {
      var host = BuildWebHost(args);

      using (var scope = host.Services.CreateScope())
      {
          var db = scope.ServiceProvider.GetService<ShortenerContext>();
          db.Database.Migrate();
      }

      host.Run();
  }

  public static IWebHost BuildWebHost(string[] args)
  {
      return WebHost.CreateDefaultBuilder(args)
          .UseStartup<Startup>()
          .Build();
  }
}

One way to run migrations in 1.x is to just add something like this in app startup:

public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            ShortenerContext db)
{
    db.Database.Migrate();
    //Rest omitted
}

This will execute all pending migrations against the database on startup.


In you Start-up method add this code

 using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetService<AppDBContext>(); 
            context.Database.Migrate(); 
        }

This will execute and update all migrations on production


  1. Check the DB table "__EFMigrationsHistory" to figure out the last run migration
  2. In Visual Studio, pick Tools > NuGet Package Manager > Package Manager Console
  3. Run script-migration -From "last_migration_name" -To "current_migration_name" or script-migration -idempotent
  4. Visual Studio will open a new tab with the generated SQL script, run it on your DB