如何正确运行迁移和使用entity framework核心种子docker MySql DB

我在我的ASP.NET核心解决scheme中实现了数据库迁移,因为它在以下问题中被推荐: 在ASP.NET 5中使用EF7进行数据库种子模式

我的解决scheme是设置为在Linux泊坞窗上工作,应用程序依赖于在Docker撰写文件中configuration的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中发生types“MySql.Data.MySqlClient.MySqlException”的exception,但未在用户代码中处理

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

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

编辑:

如果我改变这个问题的迁移方法: 不能得到UserManager类而不是以前的错误我得到这个:

在System.Private.CoreLib.ni.dll中发生types“System.AggregateException”的exception,但未在用户代码中处理

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

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