.net - 如何在 ASP.NET 启动时重试运行 EFCore Migrate?

标签 .net entity-framework-core ef-core-3.1 ef-core-3.0 ef-core-5.0

所以我想在 Azure 应用服务首次启动时运行 EF 迁移。以下代码可以正常工作:

public class Program
{
    public static void Main(string[] args)
    {
        ...
        var host = CreateHostBuilder(args).Build();
        using (var scope = host.Services.CreateScope())
        using (var context = scope.ServiceProvider.GetService<MyContext>())
        {
             context.Database.Migrate();
        }
        host.Run();
        ...
     }
 }

但是,由于数据库在 Azure 上作为无服务器实例运行,如果它当前暂停,则需要重试(因为第一次连接尝试失败)。

服务启动后,对于请求,我使用 EnableRetryOnFailure 配置了重试 - 它按预期工作:

services.AddDbContext<MyContext>(options =>
    {
        options.UseSqlServer(Configuration["...."],
           sqlServerOptionsAction: sqlOptions =>
           {
               sqlOptions.EnableRetryOnFailure(
                   maxRetryCount: 5,
                   maxRetryDelay: TimeSpan.FromSeconds(5),
                   errorNumbersToAdd: null);
           });
    });

那么我可以在 Program.Main() 中使用类似的东西来处理应用服务启动迁移吗?

非常感谢!

最佳答案

解决这个问题的一种方法是使用 Polly

您可以创建如下策略:

    var migrateDbPolicy = Policy
        .Handle<Exception>()
        .WaitAndRetry(4, retryAttempt => TimeSpan.FromSeconds(retryAttempt));

    migrateDbPolicy.Execute(() =>
    {
        context.Database.Migrate();
    });

因此,如果您在策略中设置的异常被捕获,那么任何运行到 execute 方法的代码都会被重试。

Polly 是 Microsoft 信任的非常强大的库。上面的例子是一个非常基本的例子。您可以对每种类型的异常应用不同的策略(不建议使用通用异常)。您可以有不同的等待时间等。

我建议您花一些时间深入研究。

关于.net - 如何在 ASP.NET 启动时重试运行 EFCore Migrate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64990555/

相关文章:

.net - 在实例化时赋予类唯一 ID : .Net

c# - 运行时的 .NET CLR/Framework 检测

c# - StreamReader 与 BinaryReader?

c# - Entity Framework 核心 : Fail to update Entity with nested value objects

c# - EF 核心 3 : Configure backing field of navigation property

.net - EF 核心 : multiple many-to-many relationships between the same entities

.net - 如何在多项目 sln 模板 Visual Studio 2015 中添加现有项目

c# - 如何根据条件按 1 个表达式或 2 个表达式排序?

c# - 在同一个项目中同时使用 AddDbContextFactory() 和 AddDbContext() 扩展方法

sql-server - Entity Framework 核心2.0 : How to configure abstract base class once