【问题标题】:Entity Framework Multi-Tenancy and dynamic schema实体框架多租户和动态模式
【发布时间】:2015-12-03 23:24:41
【问题描述】:

我对具有多个架构名称的实体框架和 DBContext 有疑问。它仅在我删除 dbo.__MigrationHistory 表或特定条目时才有效。

一开始是我的 DatabaseContext:

public class AppTenantDatabaseContext : DbContext, IServiceStatusDatabaseContext, IDbModelCacheKeyProvider
{
    public DbSet<Container> Items{ get; set; }

    protected string _prefix;

    public AppTenantDatabaseContext(string prefix, string connectionStringName) : base(connectionStringName)
    {
        this.Configuration.LazyLoadingEnabled = false;
        _prefix = prefix;
        System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists<AppTenantDatabaseContext>());
    }

    public AppTenantDatabaseContext(string prefix) : base("AppFramework")
    {
        this.Configuration.LazyLoadingEnabled = false;
        _prefix = prefix;
        System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists<AppTenantDatabaseContext>());
    }

    public AppTenantDatabaseContext() : this(string.Empty) { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema(this._prefix);            
        modelBuilder.Entity<Container>().ToTable("Container", schemaName: _prefix);
        base.OnModelCreating(modelBuilder);
    }

    public string CacheKey
    {
        get { return this._prefix; }
    }
}

如果我运行 DBContext,则会在表 __MigrationHistory 中为包含架构的模型的完整类名的 ContextKey 添加一个条目。如果我想为另一个模式创建表,代码会在异常中运行,因为模型不同。可以理解。

现在我的问题: 如何在不删除迁移历史表的情况下实现它?

在我看来,如果为每个模式名称而不是“dbo”创建 __MigrationHistory 表,或者如果 __MigrationHistory 表包含与类名称组合的每个模式名称的条目,它可能会起作用。我该怎么做?

感谢您的帮助!

【问题讨论】:

    标签: c# sql-server asp.net-mvc entity-framework


    【解决方案1】:

    如何在不删除迁移历史表的情况下实现它?

    你可以和Database.SetInitializer&lt;MyContext&gt;(null);一起玩。

    例如if (String.IsNullOrEmpty(_prefix) ) {...}

    这将允许:

    使用迁移历史表,但不删除它

    但这将不允许与迁移一起使用,不适用于所有前缀,除了默认前缀。

    PS:使用多个 DB 可能比使用多个模式更容易。

    【讨论】:

    • 有没有办法通过可用的迁移来解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多