![](/img/trans.png)
[英]Why do we use DependecyInjection instead of OnConfiguring Method in the DbContext?
[英]How do I set the OnConfiguring method in my DbContext without any hardcoded connection string?
我使用了多个关于如何设置 MySql 服务的示例,但几乎在每个示例中(包括 Microsoft),它们都使用硬编码的连接字符串。
这是我的启动:
services.AddDbContext<DbContext>(options =>
{
options.UseMySql(configuration.GetConnectionString("DefaultConnection"),
mysqlOptions =>
{
mysqlOptions.ServerVersion(new ServerVersion(new Version(8, 0, 18)));
});
});
每当我尝试Update-Database
我都会看到一个错误,告诉我没有设置密码
MySql.Data.MySqlClient.MySqlException (0x80004005): 用户 'root'@'localhost' 的访问被拒绝(使用密码:YES)。
环顾四周后,我发现了一个名为OnConfiguring
的可覆盖方法,但我想以动态方式设置连接字符串,因为如果我改变我的环境,我希望该字符串也改变。
这是我发现几乎所有带有硬编码字符串的示例(例如https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core.html )
如果未配置,则需要初始化配置。
这可以通过覆盖OnConfiguring
中的OnConfiguring
方法来DbContext
。
通过这种方式,您可以拥有将在应用程序运行时拉取的全局应用程序配置。 并在进行 Db 迁移时使用本地配置。
尝试这个
public class YourContext: DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (options.IsConfigured == false)
options.UseMysql({YOUR_CONNECTION_STRING});
}
}
在配置文件中,您应该有一个 ConnectionStrings 指向您的数据库和其他选项。
"ConnectionStrings": {
"DefaultConnection": "server=127.0.0.1;uid=root;pwd=12345;database=test"
},
当您使用 configuration.GetConnectionString 时,您正在从配置部分查找一个值。
在 startup.cs 试试这个
public class Startup
{
private readonly IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
// This method gets called by the runtime. Use this method to add services to the
container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MainContext>(options =>
options.UseOracle(_config["CONNECTION_STRING"]));
}
}
并在您的 Context ctor 执行此操作
public MainContext(DbContextOptions<MainContext> options) : base(options) { }
根据评论,我认为您希望将 EF Core 相关类分离到不同的程序集。
在UseMySql
有一个配置MigrationsAssembly
的选项。 您可以在此处获得更多详细信息
这是 SQL Server 的伪代码。
services.AddDbContext<EFCoreDemoContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
assembly => assembly.MigrationsAssembly(typeof(EFCoreDemoContext).Assembly.FullName));
});
我正在解决您问题的这一部分:
“环顾四周后,我发现了一个名为 OnConfiguring 的可覆盖方法,但我想以动态方式设置连接字符串,因为如果我改变我的环境,我希望该字符串也改变。”
为了解决将连接字符串放入 DbContext 类中的 OnConfiguring 方法的问题,我只是像这样将 IConfiguration 传递到 DbContext 构造函数中。
private readonly IConfiguration _config;
public CoreDbContext(IConfiguration config)
{
_config = config;
}
public CoreDbContext(DbContextOptions<CoreDbContext> options,
IConfiguration config) : base(options)
{
_config = config;
}
然后在 OnConfiguring 方法中,我从构造时注入的配置对象中提取连接字符串。 像这样:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_config.GetConnectionString("YourKeyValueForConnStringInAppSettings.json"));
}
}
最后这里是我的环境/项目的详细信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.