Skip to content

Read relevant DbContextOptions from IConfiguration #849

@divega

Description

@divega

We should make the following pattern work:

{
    "EntityFramework": {
        "MyContext": { 
            "ConnectionString": 
"Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    }
}
// Startup.ConfigureServices:
services.AddEntityFramework(configuration)
    .AddSqlServer()
    .AddDbContext<MyContext>();

// MyDbContext.OnConfiguring:
modelBuilder.UseSqlServer(); //Matches "EntityFramework:MyContext:ConnectionString" by convention

Lacking the ability to read the connection string from configuration you are forced to read it explicitly in Startup.cs, e.g. with configuration.Get("EntityFramework:MyContext:ConnectionString").

Implementation details:

  1. AddEntityFramework only captures the IConfiguration argument and flows it through the EntityServicesBuilder to AddDbContext.
  2. AddDbContext will stick an IConfigureOptions<DbContextOptions> into DI with configuration Order (precedence) which will read all sub keys under "EntityFramework:MyContext" into a property bag into the DbContextOptions instance.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions