ASP - Core Migrate EF Core SQL DB on Startup

后端 未结 11 915
故里飘歌
故里飘歌 2020-12-01 02:32

Is it possible to have my ASP Core Web API ensure the DB is migrated to the latest migration using EF Core? I know this can be done through the command line, but I want to

11条回答
  •  攒了一身酷
    2020-12-01 03:17

    I followed the IStartupFilter approach to have a generic way for migrating any context.

     public class DataContextAutomaticMigrationStartupFilter : IStartupFilter
      where T : DbContext
    {
        /// 
        public Action Configure(Action next)
        {
            return app =>
            {
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    scope.ServiceProvider.GetRequiredService().Database.SetCommandTimeout(160);
                    scope.ServiceProvider.GetRequiredService().Database.Migrate();
                }
                next(app);
            };
        }
    }
    

    Now we're able to register the DataContexts and migration in the following way:

    1st context

     services.AddDbContext(options => options.UseSqlServer(configuration.GetConnectionString("ConsumerConnection")), ServiceLifetime.Transient);
        services.AddTransient>();
    

    2nd context

    services.AddDbContext(options => options.UseSqlServer(configuration.GetConnectionString("UserConnection")), ServiceLifetime.Transient);
    services.AddTransient>();
    

    ..and so on..

    The culprit of IStartupFilter is that it only allows synchronous execution of code. For database migrations this is not an issue since we have a synchronous Migrate() method.

提交回复
热议问题