使用appsettings.json配置DbContext映射

asp.net-core c# entity-framework entity-framework-core

我正在使用.netCore和Entity Framework從SQL數據庫中獲取一些數據。
我已經設置了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; }
}

並通過以下設置將其註入我的控制器

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

現在, DashboardData類使用Table Attirbute連接到正確的表和模式。

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

我想做的是將這兩個字符串“TableName”和“dbo”提取到我的appsettings.json配置中。我已經將配置添加到appsettings,創建了TableConfiguration類並設置了依賴注入:

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"));

是否可以在DasboardData屬性中註入或以其他方式使用配置?

一般承認的答案

在你的Startup.cs

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

然後,將IOptions<TableConfiguration> tableConf注入您的上下文並存儲它以供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; }
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow