2016-11-22 65 views
2

我正在使用.netCore和实体框架从SQL数据库中获取一些数据。
我已经建立了DbContext使用appsettings.json来配置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 
{ 
    ... 
} 

我想什么做的,就是这两个字符串“表名”和“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属性中的配置?

+0

什么的EntityFramework的版本? – haim770

+0

我正在使用EF核心1.0.1 –

+0

[动态更改实体框架核心中的模式]的可能重复(http://stackoverflow.com/questions/39499470/dynamically-changing-schema-in-entity-framework-core) – Venky

回答

2

在你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; } 
} 
+0

正是我在找的!谢谢 –