1

我有一個包含context類的應用程序。一個是主上下文類,第二個是子上下文類。當我第一次運行應用程序時,master數據庫被生成。每當我創建一個新用戶時,與該用戶相關的數據庫就會使用子上下文類生成。例如,如果我創建10個用戶,則會使用子上下文類(如sub_db_userId)生成10個數據庫。如何爲自動生成的數據庫添加遷移?

問題是在這個複雜的結構中啓用遷移。我知道有些人會說創建新的數據庫使用外鍵關係是不合適的,但我必須處理需求。

我發現this thread在尋找如何爲單獨的上下文類啓用遷移方面非常有幫助,但在我的方案中,由於數據庫名與用戶標識符相關,因此它不會將更改應用到現有數據庫。相反,將更改應用到現有的子數據庫,它將創建新的數據庫,而不需要像這樣的用戶標識sub_db_。我該如何解決這個問題?

下面給出了爲每個用戶創建新數據庫的方式。

我的上下文類:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
{ 
    public ApplicationDbContext() 
     : base("DefaultConnection", throwIfV1Schema: false) {} 
} 

public class SubDbContext : DbContext 
{ 
    public DbSet<Country> Countries { get; set; } 
    public DbSet<City> Cities { get; set; } 

    public SubDbContext() : base("SubDatabaseConnection") 
    { 
    } 

    public SubDbContext(string connectionString) : base(connectionString) 
    { 
     Database.SetInitializer<SubDbContext>(new 
          CreateDatabaseIfNotExists<SubDbContext>()); 
    } 
} 

連接字符串:

<add name="DefaultConnection" 
    connectionString="Data Source=.\SQLExpress;Initial Catalog=master_db;Integrated Security=True" 
    providerName="System.Data.SqlClient" /> 
<add name="SubDatabaseConnection" 
    connectionString="Data Source=.\SQLExpress;Initial Catalog={0};Integrated Security=True" 
    providerName="System.Data.SqlClient" /> 
</connectionStrings> 

我使用{0},它們的目的。如何啓用遷移並將更改應用到現有數據庫?

修改:我鏈接表到數據庫中Register動作是這樣的:

SubDbContext newContext = new SubDbContext(string.Format(userDatabase, "sub_db_" + userId)); 
newContext.Countries.FirstOrDefault(); 
newContext.Cities.FirstOrDefault(); 
+0

您是否知道可能存在的所有用戶特定數據庫你的「主」數據庫(不要與sql-server的主數據庫混淆)? –

+0

對不起,我沒有得到你?所有用戶都存在於我的主數據庫中。 –

回答

1

DbContext爲所有子數據庫是SubDbContext。所以你必須啓用基於其中之一的遷移。然後把這個代碼Configuration類:

internal sealed class Configuration : DbMigrationsConfiguration<SubDbContext> 
{ 
    public Configuration() 
    { 
     AutomaticMigrationsEnabled = true; 
    } 
} 

,並把這個代碼到SubDbContext構造:

Database.SetInitializer<SubDbContext>(new MigrateDatabaseToLatestVersion<SubDbContext, Configuration>()); 

這意味着,當發現新的手動添加Migration每個數據庫, 然後再嘗試遷移它。

,你也可以使用這個approache太:

寫這段代碼在的Application_Start

var context = new SubDbContext("your generated connection string"); 
var initializeMigrations = new MigrateDatabaseToLatestVersion<SubDbContext, Configuration>(); 

initializeMigrations.InitializeDatabase(context); 

我希望你覺得它有用。