6

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 Answer 1

15

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Finally, something that is really improved from EF 6
is it override tables on production server?
For EF core, if the database migration project is created as a seperate project, configure the dbcontext with MigrationsAssembly options will make it work. services.AddDbContext<SampleDbContext>(opt => opt.UseSqlServer(dbConnectionString, x => x.MigrationsAssembly("SampleApi.DbMigration")));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.