【问题标题】:How do I set the OnConfiguring method in my DbContext without any hardcoded connection string?如何在没有任何硬编码连接字符串的情况下在我的 DbContext 中设置 OnConfiguring 方法?
【发布时间】:2020-04-19 11:21:50
【问题描述】:

我使用了多个示例来说明如何设置 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

【问题讨论】:

  • 您能在配置文件中显示您的 connectionString 的外观吗?
  • 为什么在从配置中检索连接字符串时将其称为硬编码?
  • 错误是用户没有权限连接到服务器'localhost'。要为不同的环境使用不同的连接,您可以在不同的appsettings.{env}.json文件中配置连接字符串。stackoverflow.com/questions/41267506/…

标签: c# asp.net-core entity-framework-core


【解决方案1】:

如果没有配置,需要初始化配置。

这可以通过覆盖DbContext 中的OnConfiguring 方法来完成。

通过这种方式,您可以拥有将在运行应用程序时拉取的全局应用程序配置。并在进行 Db 迁移时使用本地配置。

试试这个

public class YourContext: DbContext
{

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        if (options.IsConfigured == false)
            options.UseMysql({YOUR_CONNECTION_STRING});
    }
}

【讨论】:

  • 对 OnConfiguring 中的硬编码连接字符串非常不舒服。似乎必须有一种方法可以从 appsettings.json、secrets 或其他任何内容中获取字符串。有人知道怎么做吗?
【解决方案2】:

基于comment,我认为您希望将 EF Core 相关类分离到不同的程序集中。

UseMySql 中有一个配置MigrationsAssembly 的选项。您可以获取更多详情here

这是 SQL Server 的伪代码。

services.AddDbContext<EFCoreDemoContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
            assembly => assembly.MigrationsAssembly(typeof(EFCoreDemoContext).Assembly.FullName));
});

【讨论】:

    【解决方案3】:

    我正在解决您问题的这一部分:

    “环顾四周后,我发现了一个名为 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"));
            }
        }
    

    最后是我的环境/项目的详细信息:

    • Windows 10 机器
    • Visual Studio 2022(版本 17.0.4)
    • ASP.NET Core Web API
    • .NET 6.0
    • HTTPS 配置
    • 选中使用控制器
    • 启用 OpenApi 支持
    • 撰写本文时的身份验证类型为无

    【讨论】:

      【解决方案4】:

      在配置文件中,您应该有一个 ConnectionStrings 指向您的数据库以及其他选项。

      "ConnectionStrings": {
         "DefaultConnection": "server=127.0.0.1;uid=root;pwd=12345;database=test"
      },
      

      当您使用 configuration.GetConnectionString 时,您正在从配置部分查找一个值。

      【讨论】:

      • 但是当我在另一个项目中工作时如何注入 IConfig 呢?
      【解决方案5】:

      在 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) { }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-02
        • 2021-02-09
        • 2011-05-18
        • 1970-01-01
        • 2021-05-13
        相关资源
        最近更新 更多