gpt4 book ai didi

c# - 使用 appsettings.json 配置 DbContext 映射

转载 作者:行者123 更新时间:2023-11-30 21:44:37 25 4
gpt4 key购买 nike

我正在使用 .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; }
}

并使用以下设置将其注入(inject)我的 Controller

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

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

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

What i would like to do, is to extract these two strings "TableName" and "dbo" into my appsettings.json configuration. I already added the configuration to appsettings, made a TableConfiguration class and setup dependency injection:

表配置.cs

public class TableConfiguration
{
public string DatabaseView { get; set; }
public string DatabaseSchema { get; set; }
}

appsettings.json

"TableConfiguration": {
"DatabaseTable": "TableName",
"DatabaseSchema": "dbo"
}

启动.cs

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

Is it possible to inject or otherwise use the configuration in the DasboardData Attribute?

最佳答案

在您的 Startup.cs 中:

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

然后,注入(inject)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; }
}

关于c# - 使用 appsettings.json 配置 DbContext 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40744245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com