【问题标题】:Use appsettings.json to configure DbContext mapping使用 appsettings.json 配置 DbContext 映射
【发布时间】:2016-11-22 14:18:10
【问题描述】:

我正在使用 .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 属性中注入或以其他方式使用配置?

【问题讨论】:

标签: c# entity-framework asp.net-core entity-framework-core


【解决方案1】:

在你的Startup.cs:

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

然后,将IOptions&lt;TableConfiguration&gt; 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; }
}

【讨论】:

  • 正是我想要的!谢谢
猜你喜欢
  • 1970-01-01
  • 2017-04-14
  • 2011-11-28
  • 2018-06-18
  • 2016-04-24
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
相关资源
最近更新 更多