You need to enable JavaScript to run this app. .NET Core下运行dotnet EF CLI命令时Pomelo MySQL连接报Access denied错误
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core下运行dotnet EF CLI命令时Pomelo MySQL连接报Access denied错误

问题原因
  1. 核心触发原因:ServerVersion.AutoDetect() 方法传入的参数为空值。你代码中通过 Configuration.GetConnectionString("DefaultConnection") 读取配置文件中的连接字符串,但项目的 appsettings.json/appsettings.Development.json 内未正确配置名为 DefaultConnection 的连接项,导致读取结果为 null。AutoDetect 方法需要主动连接数据库探测版本,拿到空连接串后会尝试使用空用户名、无密码的方式连接MySQL,最终触发权限报错。
  2. 次要兼容风险:你的Entity Framework CLI工具版本为5.0.5,而项目运行时版本为6.0.0预览版,跨大版本不匹配可能引发额外的兼容异常。
修复方案
  • 优先解决配置读取问题,可任选一种方案:
    方案1:统一使用硬编码的连接串,避免读取配置失败,修改代码如下:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo { Title = "NetCoreApp.API", Version = "v1" });
                });
    
        string mySqlConnectionStr = "server=localhost; port=3306; database=alohatest; user=netcore; password=0yetcxeY7MzThobL; Persist Security Info=False; Connect Timeout=300";  
        services.AddDbContextPool<DataContext>(options => options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));
    }
    
    方案2:在配置文件中补全DefaultConnection配置,打开appsettings.json添加对应节点:
    {
      "ConnectionStrings": {
        "DefaultConnection": "server=localhost; port=3306; database=alohatest; user=netcore; password=0yetcxeY7MzThobL; Persist Security Info=False; Connect Timeout=300"
      },
      // 保留其他原有配置
    }
    
  • 修复EF工具版本不匹配问题,执行CLI命令更新全局EF工具:
    dotnet tool update --global dotnet-ef --version 6.0.0-preview.3.21201.2
    若你使用项目本地工具,去掉命令中的--global参数即可。
  • 验证修复结果,重新执行dotnet ef dbcontext info确认无报错即可。

内容的提问来源于stack exchange,提问作者German Kinen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 14:06:02