简体   繁体   English

如何在没有任何硬编码连接字符串的情况下在我的 DbContext 中设置 OnConfiguring 方法?

[英]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:最后这里是我的环境/项目的详细信息:

  • Windows 10 machine Windows 10 机器
  • Visual Studio 2022 (Version 17.0.4) Visual Studio 2022(版本 17.0.4)
  • ASP.NET Core Web API ASP.NET 核心 Web API
  • .NET 6.0 .NET 6.0
  • Configure for HTTPS配置 HTTPS
  • Use controllers checked使用控制器检查
  • Enable OpenApi support启用 OpenApi 支持
  • Authentication type at time of writing is None撰写本文时的身份验证类型为无

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我们在 DbContext 中使用 DependecyInjection 而不是 OnConfiguring 方法? - Why do we use DependecyInjection instead of OnConfiguring Method in the DbContext? 如果所有配置都在 DbContext 的 OnConfiguring 方法中,如何使用 AddDbContextPool - How to use AddDbContextPool if all configuration in OnConfiguring method of DbContext 如何在 Entity Framework Core 中将连接字符串传递给 DBContext? - How do I pass connection string to DBContext in Entity Framework Core? 如何在 dbContext OnConfiguring 生成中插入自定义代码? - How to insert custom codes in dbContext OnConfiguring generation? 如何在azure中为我的Web应用程序设置连接字符串? - how do i set the connection string for my web application in azure? 我的dbcontext不希望任何连接字符串作为输入 - My dbcontext doesn't expect any connection string as an input MVC 5-如何使用会话变量设置DbContext连接字符串? - MVC 5 - How can I set a DbContext connection string using a session variable? 如何在此方法中使用连接字符串? - How do I use a connection string in this method? 在控制台应用程序的OnConfiguring方法中使用依赖注入获取连接字符串? - Getting connection-string using Dependency Injection in OnConfiguring method in console application? 从 appsettings.json 到实体框架 .NET 核心中的 OnConfiguring 方法的连接字符串 - Connection string from appsettings.json to OnConfiguring method in Entity Framework .NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM