2016-11-22 6 views
2

SQLデータベースからデータを取得するために.netCoreとEntity Frameworkを使用しています。
私はセットアップDbContextappsettings.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; } 
} 

と今DashboardDataクラスが正しい表とスキーマに接続するためにTable Attirbuteを使用して、次のセットアップ

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

と私のコントローラに注入しています。

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

私がやりたい何か、私のappsettings.json構成にこれら二つの文字列「テーブル名」と「DBO」を抽出することです。私はすでにTableConfigurationクラスとセットアップ依存性注入を行った、のAppSettingsに設定を追加しました:

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
+0

EntityFrameworkのバージョンは何? – haim770

+0

私はEFコア1.0.1を使用しています –

+0

[Entity Frameworkコアの動的に変化するスキーマ]の可能な複製(http://stackoverflow.com/questions/39499470/dynamically-changing-schema-inentity-framework-core) – Venky

答えて

2

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

、あなたのOnModelCreating()してコンテキストにIOptions<TableConfiguration> tableConfを注入し、後で使用するためにそれを格納します。

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

まさに私が探していたもの!ありがとうございました –

関連する問題