【问题标题】:Is there a way to run Entity Framework migrations before Hosted Services start有没有办法在托管服务启动之前运行实体框架迁移
【发布时间】:2021-02-23 08:24:29
【问题描述】:

创建 .NET Core 5 应用程序时,我通过在 Startup.Configure (...) 方法顶部执行迁移代码来运行 EF 迁移:

public class Startup 
{
    . . .
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        using (var scope = app.ApplicationServices.CreateScope())
        {
             ApplicationDbContext context = scope.ServiceProvider.GetService<ApplicationDbContext>();
             context.Database.Migrate();
        }
        . . .
    }
}

这一切都运作良好,直到我最近添加了一些依赖数据库的托管服务和迁移应用的更改。现在,如果我需要在托管服务启动之前应用迁移,我的应用会在启动时崩溃,因为托管服务在迁移运行之前启动。

有没有办法解决这个问题?有没有办法在托管服务启动之前运行迁移?

【问题讨论】:

  • 恕我直言,在您自己的HostedService 中执行迁移,请务必先注册。
  • 如果您只有一个托管服务,这可能会起作用,但如果您有更多的服务都依赖于数据库怎么办?
  • HostedServices 是串行启动的,服务提供者按照注册的顺序返回它们。 github.com/dotnet/runtime/blob/…

标签: c# .net-core entity-framework-core


【解决方案1】:

经过一番折腾,这个解决方案似乎有效,尽管我对 .NET Core Framework 的了解还不够,无法确定这是否会成为问题:

public class Program
{
    public static void Main(string[] args)
    {
        IHost host = CreateHostBuilder(args).Build();

        IServiceScopeFactory scopeFactory = host.Services.GetService<IServiceScopeFactory>();
        using (var scope = scopeFactory.CreateScope())
        {
            ApplicationDbContext context = scope.ServiceProvider.GetService<ApplicationDbContext>();
            context.Database.Migrate();
        }
        host.Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

【讨论】:

  • 这将是我建议的方法。在调用Run 之前调用迁移将确保在托管服务启动之前完成迁移。
猜你喜欢
  • 2014-10-18
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2012-03-06
  • 2014-12-19
  • 2021-01-16
相关资源
最近更新 更多