[英]Change Database Schema Name at Runtime
目前,在我的實體中,我有以下表定義:
[Table("SchemaName.SomeTable")]
我需要能夠在運行時更改此模式名稱。 我嘗試分配一個變量,但它會引發錯誤。
作為第二次嘗試,我刪除了Table
聲明,而是在我的上下文的OnModelCreating
中嘗試使用以下內容進行設置:
modelBuilder.Entity<MY_VIEW>().ToTable("MYSCHEMA.MYVIEW");
這可行,但是,我現在希望能夠在運行時通過我的 controller 更改它,因為 OnModelCreating 只觸發一次。
為了使OnModelCreating
為不同的模式運行,您需要覆蓋IModelCacheKeyFactory
的默認行為
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
{
options.ReplaceService<IModelCacheKeyFactory, SchemaModelCacheKeyFactory>();
});
}
}
public class DatabaseOptions
{
public string Schema { get; set; }
}
public class ApplicationDbContext : DbContext
{
public string Schema { get; }
public ApplicationDbContext(DbContextOptions options, IOptions<DatabaseOptions> databaseOptions)
: base(options)
{
Schema = databaseOptions.Value.Schema;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MY_VIEW>().ToTable($"{Schema}.MYVIEW");
}
}
public class SchemaModelCacheKeyFactory : ModelCacheKeyFactory
{
public SchemaModelCacheKeyFactory(ModelCacheKeyFactoryDependencies dependencies)
: base(dependencies)
{
}
public override object Create(DbContext context)
{
if (context is ApplicationDbContext applicationDbContext)
{
return new SchemaModelCacheKey(context, applicationDbContext.Schema);
}
else
{
return base.Create(context);
}
}
}
public class SchemaModelCacheKey : ModelCacheKey
{
public SchemaModelCacheKey(DbContext context, string schema) : base(context)
{
_schema = schema;
}
private readonly string _schema;
protected virtual bool Equals(SchemaModelCacheKey other) => _schema == other._schema && base.Equals(other);
public override bool Equals(object obj) => (obj is SchemaModelCacheKey otherAsKey) && Equals(otherAsKey);
public override int GetHashCode() => base.GetHashCode() + _schema.GetHashCode();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.