[英]How do I set the OnConfiguring method in my DbContext without any hardcoded connection string?
I'm using multiple examples on how to set up my MySql service but in almost every one (including the Microsoft), they are using a hard coded connection string.我使用了多个关于如何设置 MySql 服务的示例,但几乎在每个示例中(包括 Microsoft),它们都使用硬编码的连接字符串。
This is my startup:这是我的启动:
services.AddDbContext<DbContext>(options =>
{
options.UseMySql(configuration.GetConnectionString("DefaultConnection"),
mysqlOptions =>
{
mysqlOptions.ServerVersion(new ServerVersion(new Version(8, 0, 18)));
});
});
And whenever I try to Update-Database
I see an error telling me that there's no password setted每当我尝试Update-Database
我都会看到一个错误,告诉我没有设置密码
MySql.Data.MySqlClient.MySqlException (0x80004005): Access denied for user 'root'@'localhost' (using password: YES). MySql.Data.MySqlClient.MySqlException (0x80004005): 用户 'root'@'localhost' 的访问被拒绝(使用密码:YES)。
After looking around a bit I found an overrideable method called OnConfiguring
, but I want to set the connection string in a dynamic way, cause If I change my environment, I want that string to change too.环顾四周后,我发现了一个名为OnConfiguring
的可覆盖方法,但我想以动态方式设置连接字符串,因为如果我改变我的环境,我希望该字符串也改变。
This is where I found almost every example with hardcoded strings (ex. https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core.html )这是我发现几乎所有带有硬编码字符串的示例(例如https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core.html )
You need to init configuration if not configured.如果未配置,则需要初始化配置。
This can be done by overriding the OnConfiguring
method in DbContext
.这可以通过覆盖OnConfiguring
中的OnConfiguring
方法来DbContext
。
This way you can have global application configuration that will be pulled when application is ran.通过这种方式,您可以拥有将在应用程序运行时拉取的全局应用程序配置。 And use local configuration when doing Db migration.并在进行 Db 迁移时使用本地配置。
Try this尝试这个
public class YourContext: DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (options.IsConfigured == false)
options.UseMysql({YOUR_CONNECTION_STRING});
}
}
in configuration file, you should have a ConnectionStrings that points to your database with other options.在配置文件中,您应该有一个 ConnectionStrings 指向您的数据库和其他选项。
"ConnectionStrings": {
"DefaultConnection": "server=127.0.0.1;uid=root;pwd=12345;database=test"
},
When you use configuration.GetConnectionString, you are looking up a value from the configuration section.当您使用 configuration.GetConnectionString 时,您正在从配置部分查找一个值。
Try this at startup.cs在 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"]));
}
}
And do that at your Context ctor并在您的 Context ctor 执行此操作
public MainContext(DbContextOptions<MainContext> options) : base(options) { }
Based on the comment , I think you want to separate the EF Core related classes to a different assembly.根据评论,我认为您希望将 EF Core 相关类分离到不同的程序集。
In the UseMySql
there is an option to configure MigrationsAssembly
.在UseMySql
有一个配置MigrationsAssembly
的选项。 You can get more details here您可以在此处获得更多详细信息
Here is pseudo-code for SQL Server.这是 SQL Server 的伪代码。
services.AddDbContext<EFCoreDemoContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
assembly => assembly.MigrationsAssembly(typeof(EFCoreDemoContext).Assembly.FullName));
});
I am addressing this portion of your question:我正在解决您问题的这一部分:
"After looking around a bit I found an overrideable method called OnConfiguring, but I want to set the connection string in a dynamic way, cause If I change my environment, I want that string to change too." “环顾四周后,我发现了一个名为 OnConfiguring 的可覆盖方法,但我想以动态方式设置连接字符串,因为如果我改变我的环境,我希望该字符串也改变。”
In order to solve getting the connection string into the OnConfiguring method inside your DbContext class I simply passed IConfiguration into the DbContext constructor like this.为了解决将连接字符串放入 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;
}
Then in the OnConfiguring method I pulled the connection string from that config object injected at construction.然后在 OnConfiguring 方法中,我从构造时注入的配置对象中提取连接字符串。 Like this:像这样:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_config.GetConnectionString("YourKeyValueForConnStringInAppSettings.json"));
}
}
Finally here are details of my environment / Project:最后这里是我的环境/项目的详细信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.