我正在使用.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属性中注入或以其他方式使用配置?
答案 0 :(得分:3)
在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; }
}