2011-06-09 146 views
13

另一個'實體類型'x'沒有定義密鑰'的問題,但我在屬性上設置了[Key]屬性,所以我有點困惑。實體類型沒有定義密鑰

這裏是我的實體和上下文類:

namespace DoctorDB.Models 
{ 
    public class Doctor 
    { 
     [Key] 
     public string GMCNumber; 
     [Required] 
     public string givenName; 
     [Required] 
     public string familyName; 
     public string MDUNumber; 
     public DateTime MDUExpiry; 
     public string MDUCover; 
    } 

    public class DoctorContext : DbContext 
    { 
     public DbSet<Doctor> Doctors { get; set; } 
    } 
} 

當我去創造我的控制器,我選擇與使用該實體和語境實體框架方法創建它:

enter image description here

,我得到這個錯誤:

enter image description here

我唯一的想法就是你是否無法成功地在字符串屬性上使用[Key]。如果你現在還不夠公平,我會努力工作的,但如果有人能以這種或那種方式證實這一點,我會很感激。

回答

16

您需要將GMCNumber更改爲屬性而非字段。

+0

我的模型包含在它的屬性,而不是字段。和我得到相同的錯誤。建議? – Zeeshan 2013-12-13 07:32:02

+0

我建議你問你自己的問題發佈你的代碼和完整的錯誤信息。 – codingbadger 2013-12-13 07:48:13

12

爲了幫助澄清,這條線:

public string GMCNumber;

需求,成爲:

​​

3

我遇到了同樣的錯誤消息時我已經定義的屬性爲私有。

1

今天面對類似的問題後,我遇到了這個帖子。問題在於我在將[Key]屬性添加到我的模型並且沒有編譯之後嘗試創建腳手架。一旦我編寫了[Key]屬性,腳手架就產生了。

0

當我使用不是[Key]字符串的屬性時,我得到相同的錯誤。

這裏有一個攝製:

public class Doctor 
{ 
    [Key] 
    public Identity ID { get; set; }  
    public string Address { get; set; } 
} 

public class Identity 
{ 
    [Key] 
    public string GivenName { get; set; } 
    [Key] 
    public string FamilyName { get; set; } 
} 

在構建時出現的錯誤,而是當網站負載:

An exception of type 'System.InvalidOperationException' occurred in System.Web.OData.dll but was not handled in user code

Additional information: The entity 'Doctor' does not have a key defined.

相關問題