【发布时间】:2017-12-24 18:12:25
【问题描述】:
我想在 ASP.NET Core 2.0 和 EntityFramework Core 2.0 中的应用程序启动时自动运行数据库迁移。
我找到了Run database migrations using Entity Framework core on application start。但是,我的连接字符串存储在环境变量中,因此直到在 Configure 方法中调用 .AddEnvironmentVariables() 才能找到它们。
如何调用the db.Database.Migrate() 或如何通过持续部署和暂存环境正确进行数据库迁移(在 Azure Web App 中)?
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();
// }
}
【问题讨论】:
-
为什么不在
Configure()方法的最后调用db.Database.Migrate()呢?设置连接字符串后。 -
如果我将
ClientContext db参数添加到Configure方法,ClientContext将在Configure调用之前被实例化。ClientContext获取options作为构造函数参数,它尝试在配置Configuration对象(或实例化事件)之前检索AppService连接字符串。还是我的理解有误?
标签: asp.net entity-framework asp.net-core entity-framework-core