Read DbContextOptions value in Entity Framework core constructor

connection-string dbcontext entity-framework-core options

Question

In my asp.net core service, I have this in the startup

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

and to make it works, I created also this snippet:

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

My problem now is: in "other stuff here" section, how can I read the options value and retrieve my connection string? Since there another dll and not the same project, I can't just read it again from the appsettings.json.

If I break my code during a debug session, I can see the connection string in the value inside this object, but I don't know how to get it properly. I see this value inside the "Extension" attribute of the options object.

So, how can I read the DbContextOptions value?

1
2
2/15/2018 9:55:43 AM

Accepted Answer

So, how can I read the DbContextOptions value?

You can (not publicly but using some EF Core internal infrastructure objects, in particular RelationalOptionsExtension class), but you don't need to.

To get the connection information, simply use context Database property and GetDbConnextion method:

public Mydb_Context(DbContextOptions<Mydb_Context> options) : base(options)
{
    //other stuff here
    var connectionString = this.Database.GetDbConnection().ConnectionString;
}
3
2/15/2018 1:23:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow