.NET Core下运行dotnet EF CLI命令时Pomelo MySQL连接报Access denied错误
问题原因
- 核心触发原因:
ServerVersion.AutoDetect()方法传入的参数为空值。你代码中通过Configuration.GetConnectionString("DefaultConnection")读取配置文件中的连接字符串,但项目的appsettings.json/appsettings.Development.json内未正确配置名为DefaultConnection的连接项,导致读取结果为null。AutoDetect方法需要主动连接数据库探测版本,拿到空连接串后会尝试使用空用户名、无密码的方式连接MySQL,最终触发权限报错。 - 次要兼容风险:你的Entity Framework CLI工具版本为5.0.5,而项目运行时版本为6.0.0预览版,跨大版本不匹配可能引发额外的兼容异常。
修复方案
- 优先解决配置读取问题,可任选一种方案:
方案1:统一使用硬编码的连接串,避免读取配置失败,修改代码如下:
方案2:在配置文件中补全DefaultConnection配置,打开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))); }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
相关产品推荐
相关产品推荐

