I would like to automatically run a database migration on application start in ASP.NET Core 2.0 and EntityFramework Core 2.0.
I have found Run database migrations using Entity Framework core on application start. However, my connection strings are stored in the environment variables so they would not be found until the .AddEnvironmentVariables() are called in the Configure method.
How to call the db.Database.Migrate() or how to properly do the database migration (in Azure Web App) via Continuous Deployment and staging environments?
public class Startup
{
private IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ClientContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("AppService")));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
this.Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
}
// public void Configure(IApplicationBuilder app, ClientContext db)
// {
// db.Database.Migrate();
// }
}
db.Database.Migrate()at the end of theConfigure()method? After connection strings are set.ClientContext dbparameter to theConfiguremethod, theClientContextwill get instantiated before theConfigurecall is made. TheClientContextgets theoptionsas a constructor parameter which tries to retrieve theAppServiceconnection string before theConfigurationobject is configured (or event instantiated). Or is my understanding wrong?