使用 appsettings.json 配置 DbContext 映射

Tho*_*ter 2 c# entity-framework entity-framework-core asp.net-core

我正在使用 .netCore 和实体框架从 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; }
}
Run Code Online (Sandbox Code Playgroud)

并使用以下设置将其注入我的控制器

services.AddDbContext<DashboardContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DashboardDatabase")));
Run Code Online (Sandbox Code Playgroud)

现在,该类DashboardData使用TableAttirbute 连接到正确的表和架构。

[Table("TableName", Schema = "dbo")]
public partial class DashboardData
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我想做的是将这两个字符串“TableName”和“dbo”提取到我的 appsettings.json 配置中。我已经将配置添加到 appsettings,创建了 TableConfiguration 类并设置依赖项注入:

表配置.cs

public class TableConfiguration
{
    public string DatabaseView { get; set; }
    public string DatabaseSchema { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

应用程序设置.json

"TableConfiguration": {
    "DatabaseTable": "TableName",
    "DatabaseSchema": "dbo"
} 
Run Code Online (Sandbox Code Playgroud)

启动.cs

services.Configure<TableConfiguration>(Configuration.GetSection("TableConfiguration"));
Run Code Online (Sandbox Code Playgroud)

是否可以注入或以其他方式使用 DasboardData 属性中的配置?

hai*_*770 5

在你的Startup.cs

services.Configure<TableConfiguration>(Configuration.GetSection("TableConfiguration"));
Run Code Online (Sandbox Code Playgroud)

然后,注入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; }
}
Run Code Online (Sandbox Code Playgroud)