【问题标题】:How to properly run migrations and seed a docker MySql DB using Entity Framework Core如何使用 Entity Framework Core 正确运行迁移并为 docker MySql DB 播种
【发布时间】:2017-08-13 05:10:53
【问题描述】:

我在我的 ASP.NET 核心解决方案中实现了数据库迁移,正如以下问题中所推荐的那样:Pattern for seeding database with EF7 in ASP.NET 5

我的解决方案是为在 linux docker 上工作而设置的,该应用程序依赖于在 docker compose 文件中配置的 MySql 容器,并在第一次运行时设置。

迁移在 Startup.Configure 方法中运行为:

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
    var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
    context.Database.Migrate();
    context.EnsureSeedData();
}

但是第一次运行应用程序总是会抛出以下错误:

System.Private.CoreLib.ni.dll 中出现“MySql.Data.MySqlClient.MySqlException”类型的异常,但未在用户代码中处理

然后,如果我等待几秒钟并重新启动调试会话,代码将毫无问题地执行,并且首次运行的数据就在那里。

有没有办法在运行迁移之前等待数据库服务器准备好?

编辑:

如果我更改此问题中的迁移方法:Cannot get the UserManager class 而不是上一个错误,我得到了这个:

System.Private.CoreLib.ni.dll 中出现“System.AggregateException”类型的异常,但未在用户代码中处理

【问题讨论】:

    标签: mysql docker asp.net-core


    【解决方案1】:

    有没有办法在运行迁移之前等待数据库服务器准备好?

    在您的 Program.Main 中,您可以添加尝试打开与 MySql 的连接的代码,然后循环直到连接成功打开。

    例如:

    public static void Main()
    {
    
        MySqlConnection connection;
    
        while (true)
        {
            try
            {
                connection = new MySqlConnection("Database=mysql; Server=server;User ID=user;Password=password");
                connection.Open();
                break;
            }
            // ex.Number = 1042 when the server isn't up yet, assuming you're using MySql.Data and not some other MySql implementation
            catch (MySqlException ex) when (ex.Number is 1042)
            {
                Console.Error.WriteLine("Waiting for db.");
                Thread.Sleep(1000);
            }
        }
    
        // ... continue launching website
    
    }
    

    【讨论】:

    • 真的吗?任何推荐 Thread.Sleep 的解决方案都会被否决
    • 你完全忽略了为什么它是必要的细微差别。
    猜你喜欢
    • 2017-04-26
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2017-12-22
    • 2020-05-23
    相关资源
    最近更新 更多