使用Pomelo.EntityFramework.MySql时,EF Core连接字符串存为用户密钥报错怎么办?
解决EF Core + Pomelo MySQL连接字符串分离存储问题
错误原因
你直接在UseMySql里传入"name=ConnectionStrings:Smokey"会被Pomelo当作连接字符串本身解析,而它无法识别name这个连接字符串参数,所以抛出了Option 'name' not supported的错误。Name=xxx的写法仅适用于EF Core的工具命令(比如dbcontext scaffold),不能直接用在业务代码里。
正确的实现步骤
1. 确保用户密钥设置正确
先检查用户密钥的键是否有多余空格,正确的设置命令应该是:
dotnet user-secrets set "ConnectionStrings:Smokey" "server=localhost;user=asp;password=password;database=data"
(注意键ConnectionStrings:Smokey和值之间不要有空格)
2. 方式一:通过依赖注入配置DbContext(推荐)
在ASP.NET Core项目中,最佳实践是在Program.cs中通过DI配置DbContext,无需在DbContext的OnConfiguring里硬写逻辑:
var builder = WebApplication.CreateBuilder(args); // 注册DbContext并读取连接字符串 builder.Services.AddDbContext<SmokeyDbContext>(options => { var connectionString = builder.Configuration.GetConnectionString("Smokey"); options.UseMySql(connectionString, ServerVersion.Parse("8.0.29-mysql")); }); var app = builder.Build(); // 后续中间件配置... app.Run();
此时可以删除DbContext中的OnConfiguring方法,DI会自动完成数据库连接配置。
3. 方式二:在DbContext中注入IConfiguration读取连接字符串
如果需要保留OnConfiguring方法,可以通过构造函数注入IConfiguration来获取连接字符串:
private readonly IConfiguration _configuration; // 构造函数注入IConfiguration public SmokeyDbContext(IConfiguration configuration) { _configuration = configuration; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { var connectionString = _configuration.GetConnectionString("Smokey"); optionsBuilder.UseMySql(connectionString, ServerVersion.Parse("8.0.29-mysql")); } }
4. Scaffold命令的正确用法
你之前的Scaffold命令是正确的,EF Core工具会自动读取用户密钥中的配置:
dotnet ef dbcontext scaffold Name=ConnectionStrings:Smokey "Pomelo.EntityFrameworkCore.MySql"
生成的DbContext可能没有包含注入逻辑,你需要手动添加上面的注入代码,或者改用DI配置的方式。
总结
通过用户密钥存储敏感凭据,再通过IConfiguration读取连接字符串,就能实现凭据与代码库的分离。推荐使用DI配置DbContext的方式,更符合ASP.NET Core的设计理念。
内容的提问来源于stack exchange,提问作者Alex Dobson-Pleming
相关产品推荐
相关产品推荐

