【问题标题】:optionbuilder.IsConfigured always false on abstract dbContextoptionbuilder.IsConfigured 在抽象 dbContext 上始终为 false
【发布时间】:2022-06-28 21:12:21
【问题描述】:

我有一个用于只读操作的 dbContext 和一个用于写操作的 dbContext,针对相同的数据库表。 我尝试创建一个抽象的 dbContext,其他两个上下文继承自,以便不必复制数据库配置两次。

我像这样在 program.cs 中注入我的上下文:

builder.Services.AddDbContext<WriteContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionString")));;
builder.Services.AddDbContext<ReadOnlyContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("ReadOnlyConnectionString")));

两个上下文如下所示:

 public partial class ReadOnlyContext : AbstractContext
{
    public ReadOnlyContext()
    {
    }

    public ReadOnlyContext(DbContextOptions<AbstractContext> options)
        : base(options)
    {
    }

}

我的 AbstractContext 看起来像这样:

public abstract partial class AbstractContext : DbContext
{


    public AbstractContext()
    {
    }

    public AbstractContext(DbContextOptions<AbstractContext> options)
        : base(options)
    {
    }

    // DbSet declarations 

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
           // string connexion for reproducing the problem
            optionsBuilder.UseSqlServer("Server=devServer;Database=myDb;Integrated Security=true;Application Name=API Suivi Support;Connect Timeout=30;");
        }
    }
    // db configuration
}

当我运行应用程序时,抽象类中的条件 !optionsBuilder.IsConfigured 始终返回 true,并使用我的开发连接字符串。

如果我在没有抽象类的情况下创建两个不同的上下文并在两者中复制配置,那么一切正常。

我应该如何使用抽象类和它们自己的连接字符串来实例化每个上下文?

【问题讨论】:

  • 我对你在问什么感到困惑。您能否为您看到的意外行为添加一个简短、完整的重现?
  • 您可以将连接字符串放在&lt;connectionStrings&gt; 下的app.config/web.config 中,然后传递连接字符串设置名称而不是连接字符串文字。这样您就可以在开发和测试/生产环境之间使用配置转换。

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


【解决方案1】:

builder.Services.AddDbContext&lt;WriteContext&gt;(options =&gt; options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionString"))); 中对 UseSqlServer 的调用导致当 OnConfiguring 运行时 IsConfigured 为真。

你可以在Source of DbContextOptionsBuilder看到这个

public virtual bool IsConfigured => _options.Extensions.Any(e => e.Info.IsDatabaseProvider);

还有Source of SqlServerOptionsExtension(这是UseSqlServer调用添加的扩展名。

public override bool IsDatabaseProvider => true;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2012-03-29
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多