2015-01-21 49 views
1

我的工作,讓功能簡介頁面來顯示每個學生入學時間,但我得到這個錯誤:「實體類型沒有定義鍵」異常

enter image description here

+1

錯誤不言自明。您在學生實體中缺少主鍵。你能不能粘貼你的學生實體類 – qamar 2015-01-21 05:45:33

+0

我在SQL上沒有在Visual Studio中做過DB,所以我做了什麼是從模型中單擊EF設計師從DB,然後我從SQL獲得相同的DB。無論如何,我爲學生分配了一個主鍵。感謝您的幫助 – wadbarca 2015-01-21 05:58:17

+0

如果您在模型中定義了一個鍵,則此錯誤無意義。 – qamar 2015-01-21 06:06:08

回答

0

實體框架區分不同的對象在它們的關鍵字的上下文中。問題是Student實體沒有定義任何鍵。如果你是第一次使用的代碼也許你沒有關注任何約定的主鍵 慣例是這樣

public int EntityNameID {get;set;} 

public int Id {get;set;} 

Code First infers that a property is a primary key if a property on a class is named 「ID」 (not case sensitive), or the class name followed by "ID". If the type of the primary key property is numeric or GUID it will be configured as an identity column.

,你也可以指定[Key][1]屬性到你想要的屬性成爲您的實體的關鍵。

另一種方法是使用流利的API定義您的實體的關鍵。

modelBuilder.Entity<Student>.HasKey(s => s.Id); 
+0

(加法)如果它不遵循此規則,則可以用屬性[Key]修飾屬性。 – Andreas 2015-01-21 05:59:45

+0

我首先從SQL服務器使用數據庫如何使用您的建議修復它? – wadbarca 2015-01-21 06:00:51

+0

您應該修改您的數據庫併爲您的表定義一個主鍵@wadbarca – dotctor 2015-01-21 06:01:32

相關問題