读取 Entity Framework 核心构造函数中的 DbContextOptions 值

Read DbContextOptions value in Entity Framework core constructor

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

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

为了让它发挥作用,我还创建了这个片段:

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

我现在的问题是:在 "other stuff here" 部分,我如何读取选项值并检索我的连接字符串?由于还有另一个 dll 而不是同一个项目,我不能再从 appsettings.json.

中读取它

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

那么,如何读取 DbContextOptions 值?

So, how can I read the DbContextOptions value?

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

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

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