我想在ASP.NET Core 2.0和EntityFramework Core 2.0中的应用程序启动时自动运行数据库迁移。
我找到了Run database migrations using Entity Framework core on application start。但是,我的连接字符串存储在环境变量中,因此在.AddEnvironmentVariables()
方法中调用Configure
之前,它们将无法找到。
如何通过持续部署和登台环境调用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();
// }
}
答案 0 :(得分:3)
基于你上面的评论我会尝试这个:
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
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();
var db = serviceProvider.GetService<ClientContext>();
db.Database.Migrate();
}
这是在设置环境变量后手动解析ClientContext
,因此参数注入不会失败。
编辑:您可以按照this SO question
中的步骤解决您遇到的错误