【问题标题】:Read DbContextOptions value in Entity Framework core constructor在实体框架核心构造函数中读取 DbContextOptions 值
【发布时间】:2018-02-15 09:55:43
【问题描述】:

在我的 asp.net 核心服务中,我在启动时有这个

services.AddDbContext<Mydb_Context>(
    options => options.UseSqlServer(Configuration["Settings:ConnString"]));

为了让它工作,我还创建了这个 sn-p:

public Mydb_Context(DbContextOptions<Mydb_Context> options) : base(options)
{
    //other stuff here
}

我现在的问题是:在“此处的其他内容”部分,我如何读取选项值并检索我的连接字符串?由于有另一个 dll 而不是同一个项目,我不能从 appsettings.json 中再次读取它。

如果我在调试会话期间破坏了我的代码,我可以在该对象内的值中看到连接字符串,但我不知道如何正确获取它。我在选项对象的“扩展”属性中看到了这个值。

那么,如何读取 DbContextOptions 值?

【问题讨论】:

    标签: connection-string entity-framework-core dbcontext options


    【解决方案1】:

    那么,如何读取 DbContextOptions 值?

    您可以(不公开,但使用一些 EF Core 内部基础架构对象,特别是 RelationalOptionsExtension 类),但您不需要。

    要获取连接信息,只需使用上下文Database 属性和GetDbConnextion 方法:

    public Mydb_Context(DbContextOptions<Mydb_Context> options) : base(options)
    {
        //other stuff here
        var connectionString = this.Database.GetDbConnection().ConnectionString;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      • 2022-01-20
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      相关资源
      最近更新 更多