2014-11-04 86 views
1

這是一個帶有Entity Framework 6.1 Code First應用程序的ASP.NET MVC。ASP.NET Entity Framework Code First Migrarion

我需要我的應用程序來創建數據庫,如果它不存在和種子的表與一些數據。此外,如果使用MigrateDatabaseToLatestVersion更改模型,我需要在應用程序啓動時遷移數據庫。

在的Application_Start我有:

protected void Application_Start() 
{ 
    Database.SetInitializer(new MyAppDataInitializer()); 
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyAppDataContext, MyApp.Model.Migrations.Configuration>()); 
} 

的初始化:

public class MyAppDataInitializer: CreateDatabaseIfNotExists<MyAppDataContext> 
{ 
    protected override void Seed(MyAppDataContext context) 
    { 
     Code to add some "CREATION DATA" 
    } 
} 

這裏是遷移配置類:

public class Configuration : DbMigrationsConfiguration<MyApp.Model.DataContext.MyAppDataContext> 
    { 
     public Configuration() 
     { 
      AutomaticMigrationsEnabled = true; 
      AutomaticMigrationDataLossAllowed = true; 
      ContextKey = "MyApp.Model.DataContext.MyAppDataContext"; 
     } 

     protected override void Seed(MyApp.Model.DataContext.MyAppDataContext context) 
     { 
      Code to add some "MIGRATION DATA" 
     } 
    } 

當我的應用程序啓動時,它如預期,除了作品有一件事:

  • 如果數據庫存在,它工作的很完美,它會根據新模型更改數據庫,並使用「MIGRATION DATA」爲數據庫播種。

  • 如果數據庫不存在,它將創建數據庫,但它只會使用「遷移數據」對數據庫進行種子處理,但不會對「創建數據」進行種子處理。沒有調用inicializer中的SEED方法。

我敢肯定有什麼我做錯了,但我想不通我怎麼可以創建數據庫時不存在,它和種子一些「初始化」的數據,它僅首次插入。

然後,當更改模型時,它只會更改數據庫並添加我在遷移種子方法中設置的數據以防萬一需要。

你能幫我解決嗎?

在此先感謝。

回答

1

您正在覆蓋初始值設定項。這是一個「套」不是「添加」初始化和只能有一個..

protected void Application_Start() 
{ 
    Database.SetInitializer(new MyAppDataInitializer()); 
    // Now the initializer gets "re-set" again and MyAppDataInitializer is not used at all 
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyAppDataContext, MyApp.Model.Migrations.Configuration>()); 
} 
+0

我明白了,謝謝。所以我怎麼做我想要的?我可以問數據庫是否存在,如果不存在,只需在創建數據庫後插入創建數據?或者有像創建數據庫一樣的事件? – 2014-11-04 12:34:05

0

如果數據庫中存在與否裏面MyApp.Model.Migrations.Configuration類可以檢查。在Seed方法首先檢查數據庫是否存在,如果不是則創建數據庫然後是種子數據。

public class Configuration : DbMigrationsConfiguration<MyApp.Model.DataContext.MyAppDataContext> 
{ 
    public Configuration() 
    { 
     AutomaticMigrationsEnabled = true; 
     AutomaticMigrationDataLossAllowed = true; 
     ContextKey = "MyApp.Model.DataContext.MyAppDataContext"; 
    } 

    protected override void Seed(MyApp.Model.DataContext.MyAppDataContext context) 
    { 
     if (!context.Database.Exists()) 
      context.Database.Create(); 

     Code to add some "MIGRATION DATA" 
    } 
} 
+0

當我檢查那個事件(種子)時,它總是存在。即使當時還沒有創建數據庫... – 2014-11-04 20:44:50

+0

發佈創建數據和遷移數據的代碼 – 2014-11-05 05:57:55

+0

我的代碼在第一篇文章中。現在我已經刪除了創建代碼,因爲可以只有一個......但是如果我檢查該數據庫是否存在於Seed方法內,它總是存在。 – 2014-11-05 07:22:09

相關問題