gpt4 book ai didi

mysql - 如何使用 Entity Framework Core 正确运行迁移和播种 docker MySql DB

转载 作者:行者123 更新时间:2023-11-29 03:21:55 24 4
gpt4 key购买 nike

我在我的 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();
}

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

An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in System.Private.CoreLib.ni.dll but was not handled in user code

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

有没有一种方法可以在运行迁移之前等待数据库服务器准备就绪?

编辑:

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

An exception of type 'System.AggregateException' occurred in System.Private.CoreLib.ni.dll but was not handled in user code

最佳答案

Is there a way that it could wait for the DB server to be ready before running the migrations?

在您的 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

}

关于mysql - 如何使用 Entity Framework Core 正确运行迁移和播种 docker MySql DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42928754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com