【EntityFramework】Migration 時發生 NullReferenceException

  • 1217
  • 0
  • 2017-08-08

  前幾天專案進行資料模型變更,執行 Migration 時出現了刺眼的紅字:並未將物件參考設定為物件的執行個體

  雖然對 EntityFramework 不敢說精通,但也算是略懂略懂,第一次看到這樣的錯誤訊息。

01:EntityFramework_Migration_NullReferenceException

  前後檢查了幾次,認為在寫法上並沒有問題,而套件管理主控台又無法進行偵錯,於是決定開新專案一步一步進行除錯。

1、建立資料模型

  建立一個簡單資料模型:Student。

namespace Model
{
    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }
}

2、建立資料庫連線

  建立 LabContext 繼承 DbContext,加入屬性 Students 提供 EntityFramework 建立資料實體。

  直接使用資料庫連線字串傳入 DbContext 的建構式內。

  執行 Add-Migration:正常產生 Migration 文件。

02:LabContext_ConnectionString

3、調整資料庫連線,連線字串移動至 App.config

  開啟 App.config,加入連線字串節點:Lab。

<configuration>
    <connectionStrings>
        <add name="Lab" connectionString="Server=.;Database=Lab;Integrated Security=True;" />
    </connectionStrings>
</configuration>

  調整 LabContext,使用資料庫連線字串節點名稱傳入 DbContext 的建構式內。

  執行 Add-Migration:正常產生 Migration 文件。

03:LabContext_AppConfig_Node

4、調整資料庫連線,連線字串由類別取得

  由於進行中的專案有一個類別專門用來取得各種參數設定,在此也建立一個類別(Config)來取得資料庫連線字串。

using System.Configuration;

namespace Repository
{
    public sealed class Config
    {
        public static string LabConnectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["Lab"].ConnectionString;
            }
        }
    }
}

  調整 LabContext,使用 Config 類別取得資料庫連線字串傳入 DbContext 的建構式內。

  執行 Add-Migration:刺眼的紅字出現了!

04:LabContext_Config

  雖然還原了錯誤,但是在查找官方文件及求助 google 大神後仍然不知道錯誤為何發生…

5、起始專案設定

  在不知道過了多久以後,偶然發現此時方案的起始專案是 Model。

05:Migration_StartupProject_Model

  將起始專案改為 Repository。

  執行 Add-Migration:正常產生 Migration 文件。

06:Migration_StartupProject_Repository

6、假設與測試

  假設 EntityFramework 會抓取起始專案的 App.config。

  試著將 App.config 移至 Model 專案,並將 Model 專案設為起始專案,套件管理主控台的預設專案為 Repository。

  執行 Add-Migration 一樣可正常產生 Migration 文件。

在套件管理主控台不是已經設定了預設專案嗎?為何在 Migration 時 EntityFramework 會去抓起始專案的 App.config?

7、Package Manager Console(Visual Studio)

  確定發生原因與起始專案有關以後,終於在 Package Manager Console (Visual Studio) 得到解答。

  執行 Migration 時是可以設定起始專案的,默認為方案的起始專案。

  將起始專案改為 Model。

  執行 Add-Migration 並給定 StartupProject:正常產生 Migration 文件。

EntityFramework 執行 Migration 時會讀取起始專案的 App.config,如果不調整起始專案則需要在 Migration 時給定 StartupProject。

07:Migration_StartupProject

嘗試將自己的理解寫成文字紀錄,資料來源均來自於網路。

如有理解錯誤、引用錯誤或侵權,請多加指正與告知,讓我有更多的進步與改進的空間,謝謝!