[.NET Entity Framework] 找不到 Entity Key ???

  • 1861
  • 0

[.NET Entity Framework] 找不到 Entity Key ???

前陣子使用 WebSecurity 產生使用者 Table, 接著再使用 Entity Framework 5.0 由資料庫產生程式碼, 好玩的事情發生了, 在編譯時沒有錯誤, 當有使用到那一些由 Entity Framework T4 產生的 Domain Model 時, 就發生 Run Time Error...

Image[8]

這錯誤訊息是說, 未定義 Entity Key, 也就是 Table 的 Primary Key, 說也奇怪, 檢查一下 Entity Framework Diagram, 奇怪..., 明明有確實是有 Entity Key, 竟然沒有跟著產生出來...

Image(1)[5]

搞了半天, 原來使用 Entity Framework 在 Domain Model 操作時會去尋找他的 Entity Key, 而且它預設只認得 Id 或 EntityNameId 是該 Table 的 Key, 如果使用的 Primary Key 名稱不是以上兩個, 很抱歉, 只能自己加了..., 也就是給 Domain Model 的 Entity Key 一個 Key Attribute.

Image(2)[7]

Image(3)[5]

如上, 在 Domain Model using System.ComponentModel.DataAnnotations, 並給予 Entitty Key 一個 Key Attribute.

P.S. 為何 WebSecurity 預設產生的 Table Primary Key 不是用 Id 或 EntityNameId 呢..., 這樣不就每次用 Entity Framework Update 時就要在改一次哩... Orz...