实体框架核心错误:使用服务器“localhost”上的数据库“”连接时发生错误

Rus*_*kwa 5 c# mysql entity-framework-core asp.net-core visual-studio-2019

我做了一个ASP.NET Core 3.1基于Web的应用程序,想使用MySQL作为数据库。

我一直在关注一些关于使用MySQL database[ASP.NET Core 3.1 代码优先方法]创建的 YouTube 教程,包括来自此网站的教程:

https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-3.1&tabs=visual-studio

我创建了一个,向 Startup.cs 类DataModel Class添加了一个服务,并创建了一个实现.UseMySQLAppDBContext ClassDbContext Class

当我在包管理器控制台中运行此命令时:Add-Migration InitialDatabase应用程序正在成功创建迁移。

当我运行时update-database它抛出此异常:

fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database '' on server 'localhost'.
An error occurred using the connection to database '' on server 'localhost'.
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySQL' call.
Run Code Online (Sandbox Code Playgroud)

当我根据需要调用该EnableRetryOnFailure();函数时,遇到以下异常:

失败:Microsoft.EntityFrameworkCore.Database.Connection[20004] 使用服务器“localhost”上的数据库“”连接时发生错误。使用服务器“localhost”上的数据库“”连接时发生错误。

可能是什么问题?我哪里理解错了?

如果您有关于使用MySQL Databasewith的有用文章的链接ASP.NET Core,我将不胜感激或您对这个特定问题的帮助。

我正在使用Visual Studio IDE 2019ASP.NET Core 3.1.1

附加代码:

这是 Startup.cs 类:

private IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
    _configuration = configuration;
}

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // database connection string configuration  
    services.AddDbContextPool<AppDBContext>(options => options.UseMySql(_configuration.GetConnectionString("DatabaseConnectionString"),
        mySqlOptionsAction: options => { options.EnableRetryOnFailure(); }
        ));

    services.AddMvc();
}
Run Code Online (Sandbox Code Playgroud)

这是 appsettings.json 中的连接字符串:

  "ConnectionStrings": {
    "DatabaseConnectionString": "Server=localhost;Database=MyAppDB;user=root;Password=123;"
  }
Run Code Online (Sandbox Code Playgroud)

Yan*_*ode 0

您的连接字符串 \xe2\x80\x99t 似乎不正确,或者 EF 无法提取它。在运行更新之前,您需要检查文档并选择正确的项目。\n使用此帖子确认连接字符串:

\n\n

https://www.c-sharpcorner.com/UploadFile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/

\n\n

您可以尝试此解决方法来指定使用命令的连接,PS您需要更新 MySql 的提供程序名称:

\n\n
Update-Database -Verbose \n -ConnectionString "CONNECTIONSTRING" \n -ConnectionProviderName "System.Data.SqlClient"\n -StartupProjectName WEBSITE_PROJECT -ProjectName MIGRATION_PROJECT\n
Run Code Online (Sandbox Code Playgroud)\n