azure-mysql出错

qv7cva1a  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(349)

我正在尝试在azure上使用mysql on app,free tier(always on not enabled)在我的web应用asp.net core 2.1上运行所有挂起的迁移,但收到一个错误,如日志文件中所示:

"Microsoft.EntityFrameworkCore.Database.Connection: An error occurred using the connection to database '' on server '127.0.0.1:54184'"

我使用的mysql包是pomelo.entityframeworkcore.mysql,版本2.1.1。我正在startup类的configure方法中运行以下代码:

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

它似乎从app中mysql的环境变量中获得了正确的服务器和端口,但没有从数据库名称中获得。
更新:即使我删除代码行以应用迁移,它也不起作用。只需注入dbcontext,我就有同样的错误。这可能是因为当web应用程序启动时,应用程序中的sql还不可用。

6tr1vspr

6tr1vspr1#

问题似乎是azure通过环境变量提供的连接字符串。它将丢失参数“port”,因为端口位于服务器名称旁边,但连接字符串以这种方式无效。我做了几行代码来修复它。

public string FixAzureConnectionString(string connStr)
        {
            string goodConnStr = connStr;
            string portNumber = Regex.Match(goodConnStr, @"(?<=Data Source.+:)\d+")?.Value;
            goodConnStr += ";Port=" + portNumber;
            goodConnStr = goodConnStr.Replace(":" + portNumber, "");
            return goodConnStr;
        }

相关问题