Thomas Schneiter Thomas Schneiter - 11 days ago 5
C# Question

Use appsettings.json to configure DbContext mapping

I'm using .netCore and Entity Framework to get some data from an SQL Database.

I have setup a

DbContext


public partial class DashboardContext : DbContext
{
public NotfallDashboardContext(DbContextOptions<NotfallDashboardContext> options) : base(options) {}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DashboardData>(entity =>
{
...
}
}

public virtual DbSet<DashboardData> DashboardData { get; set; }
}


and inject it into my controller with the following setup

services.AddDbContext<DashboardContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DashboardDatabase")));


Now the
DashboardData
class uses the
Table
Attirbute to connect to the correct table and schema.

[Table("TableName", Schema = "dbo")]
public partial class DashboardData
{
...
}






What i would like to do, is to extract these two strings "TableName" and "dbo" into my appsettings.json configuration. I already added the configuration to appsettings, made a TableConfiguration class and setup dependency injection:


TableConfiguration.cs

public class TableConfiguration
{
public string DatabaseView { get; set; }
public string DatabaseSchema { get; set; }
}


appsettings.json

"TableConfiguration": {
"DatabaseTable": "TableName",
"DatabaseSchema": "dbo"
}


startup.cs

services.Configure<TableConfiguration>(Configuration.GetSection("TableConfiguration"));



Is it possible to inject or otherwise use the configuration in the DasboardData Attribute?

Answer

In your Startup.cs:

services.Configure<TableConfiguration>(Configuration.GetSection("TableConfiguration"));

Then, inject IOptions<TableConfiguration> tableConf into your context and store it for later usage by your OnModelCreating():

public class DashboardContext : DbContext
{
    private readonly TableConfiguration tableConf;

    public DashboardContext(DbContextOptions<DashboardContext> options, IOptions<TableConfiguration> tableConf) : base(options)
    {
        this.tableConf = tableConf.Value;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<DashboardData>(entity =>
        {
            entity.ToTable(this.tableConf.DatabaseTable, this.tableConf.DatabaseSchema);
        });
    }

    public virtual DbSet<DashboardData> DashboardData { get; set; }
}
Comments