Skip to content

Instantly share code, notes, and snippets.

@luebster
Last active March 20, 2019 12:40
Show Gist options
  • Save luebster/9b2802caac12bb527efc437943b02b5e to your computer and use it in GitHub Desktop.
Save luebster/9b2802caac12bb527efc437943b02b5e to your computer and use it in GitHub Desktop.
Automatically apply Entity Framework Core database migrations on app first run after restart/deploy
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
using MyApp.Data;
namespace MyApp
{
public class Program
{
public static async Task Main(string[] args)
{
var webHost = CreateWebHostBuilder(args).Build();
// create a new scope
using (var scope = webHost.Services.CreateScope())
{
// Get the dbcontext instance
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
// do the migration async
await dbContext.Database.MigrateAsync();
}
// Run the web host and start accepting requests
// there's an async overload, so we may as well use it
await webHost.RunAsync();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment