简体   繁体   English

在运行时更改数据库模式名称

[英]Change Database Schema Name at Runtime

Currently, in my entity I have the following table definition:目前,在我的实体中,我有以下表定义:

[Table("SchemaName.SomeTable")]

I need to be able to change this schema name at run-time.我需要能够在运行时更改此模式名称。 I tried assigning a variable however it throws an error.我尝试分配一个变量,但它会引发错误。

As a second attempt I removed the Table declaration and instead in the OnModelCreating of my context tried to set it with the following:作为第二次尝试,我删除了Table声明,而是在我的上下文的OnModelCreating中尝试使用以下内容进行设置:

modelBuilder.Entity<MY_VIEW>().ToTable("MYSCHEMA.MYVIEW");

This works, however, I would now like to be able to change this at run time through my controller as OnModelCreating only fires once.这可行,但是,我现在希望能够在运行时通过我的 controller 更改它,因为 OnModelCreating 只触发一次。

In order to make OnModelCreating to run for different schema you need to override the default behavior for IModelCacheKeyFactory为了使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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM