【问题标题】:Run database migrations using Entity Framework ASP.NET Core on application start在应用程序启动时使用 Entity Framework ASP.NET Core 运行数据库迁移
【发布时间】: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


【解决方案1】:

根据你上面的评论,我会试试这个:

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中的步骤解决

【讨论】:

  • 我猜ClientContext的生命周期是由运行时管理的,所以不需要添加“using”语句吧?
  • 我收到Cannot resolve scoped service 'AppService.ClientContext' from root provider.
  • 查看我上面的编辑,我也没有必要重新写出这些步骤 :-)
  • 我唯一不太高兴的是,该应用程序需要在完整的 sql 管理员下运行才能使其正常工作。但这是另一个问题。
猜你喜欢
  • 2016-11-11
  • 2017-04-26
  • 2021-12-31
  • 2017-05-16
  • 2021-01-21
  • 2019-09-03
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
相关资源
最近更新 更多