Run database migrations using Entity Framework core on application start

asp.net-core asp.net-core-mvc entity-framework-core migration

Question

Is it possible to configure StartUp.cs or project.json to run database migrations using Entity Framework Core on application start?

Now I have middleware that do this task, but it seems to make negative influence on performance because database is being checked each request received.

public class EntityFrameworkUpdateDatabaseMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ApplicationDbContext _dbContext;

    public EntityFrameworkUpdateDatabaseMiddleware(RequestDelegate next, ApplicationDbContext dbContext)
    {
        _next = next;
        _dbContext = dbContext;
    }

    public async Task Invoke(HttpContext context)
    {
        await _dbContext.Database.MigrateAsync();
        await _next.Invoke(context);
    }
}
1
6
7/9/2016 2:34:21 PM

Accepted Answer

You can do this in the config methods in your Startup.cs. The simplest way is like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>();

    // add other services        
}

public void Configure(IApplicationBuilder app, ApplicationDbContext db)
{
    db.Database.Migrate();

    // configure other services
}
13
7/9/2016 2:57:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow