2

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?

3

1 Answer 1

5

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what i was looking for! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.