11

我使用實體框架4.3的代碼先用這樣的自定義數據庫初始化:如何在實體框架4.3 Code First中禁用__MigrationHistory表的使用?

public class MyContext : DbContext 
{ 
    public MyContext() 
    { 
     Database.SetInitializer(new MyContextInitializer()); 
    } 
} 

public class MyContextInitializer : CreateDatabaseIfNotExists<MyContext> 
{ 
    protected override void Seed(MyContext context) 
    { 
     // Add defaults to certain tables in the database 

     base.Seed(context); 
    } 
} 

每當我的模式的轉變,修改我的POCO的手動映射和我手動更新我的數據庫。

當我再次運行我的申請,我得到這個錯誤:

Server Error in '/' Application.

The model backing the 'MyContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The model backing the 'MyContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

使用EFProfiler,我也注意到正在執行這些查詢:

-- statement #1 
SELECT [GroupBy1].[A1] AS [C1] 
FROM (SELECT COUNT(1) AS [A1] 
     FROM [dbo].[__MigrationHistory] AS [Extent1]) AS [GroupBy1] 

-- statement #2 
SELECT TOP (1) [Project1].[C1]   AS [C1], 
       [Project1].[MigrationId] AS [MigrationId], 
       [Project1].[Model]  AS [Model] 
FROM (SELECT [Extent1].[MigrationId] AS [MigrationId], 
       [Extent1].[CreatedOn] AS [CreatedOn], 
       [Extent1].[Model]  AS [Model], 
       1      AS [C1] 
     FROM [dbo].[__MigrationHistory] AS [Extent1]) AS [Project1] 
ORDER BY [Project1].[CreatedOn] DESC 

我如何避免這種情況?

回答

10

起初我確定是因爲你在ctor中設置了默認初始值設定項,但調查了一下,我發現初始值設定項在創建上下文時沒有運行,而是當你第一次查詢/添加某些項時。

提供的初始值設定項全部檢查模型的兼容性,所以您對它們運氣不佳。您可以輕鬆地製作自己的初始化這樣反而雖然:

public class Initializer : IDatabaseInitializer<Context> 
    { 

     public void InitializeDatabase(Context context) 
     { 
      if (!context.Database.Exists()) 
      { 
       context.Database.Create(); 
       Seed(context); 
       context.SaveChanges(); 
      } 
     } 

     private void Seed(Context context) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

這不應該檢查保持兼容,如果數據庫丟失,將創建它。

UPDATE: 「上下文」 應該是你實現的DbContext

傳遞null的
+0

謝謝Mikael。你的解決方案似乎工作。你是正面的默認'CreateDatabaseIfNotExists'只不過是'if(!context.Database.Exists()){context.Database.Create();種子(上下文); }'? –

+0

我不確定,但在沒有數據庫存在的情況下,它們會根據Sql Profiler atleast生成完全相同的SQL。 –

+0

我剛剛反編譯EntityFramework.dll以查看它的功能。看看這個要點:https://gist.github.com/3017384在調用Seed(上下文)後,最重要的缺失部分是context.SaveChanges();。感謝您指點我正確的方向! –

相關問題