使用appsettings.json配置DbContext映射

时间:2016-11-22 14:18:11

标签: c# entity-framework asp.net-core 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属性中注入或以其他方式使用配置?

1 个答案:

答案 0 :(得分:3)

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; }
}