1

我試圖創建以下對象之間的許多一對多的關係:當我運行它實體框架CodeFirst許多一對多通過DataAnnotations關係

public class Classified{ 
    [Key] 
    public int Id {get;set;}  
    public string details {get;set;} 
    public ICollection<ClassifiedRating> Ratings {get;set;} 
} 

public class User{ 
    [Key] 
    public int Id {get;set;} 
    public string Name {get;set;} 
} 

public class ClassifiedRating{ 
    [Key] 
    public User Rater {get;set;} 
    [Key] 
    public Classified Classified {get;set;} 
    public int rating {get;set;} 
}  

我收到以下錯誤:

One or more validation errors were detected during model generation: 

\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'ClassifiedRating' 
has no key defined. Define the key for this EntityType. 

\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'ClassifiedRating' 
is based on type 'RateUser' that has no keys defined. 

(以下簡稱「\ t」的的是出現在錯誤信息爲好,但我懷疑它是相關的,它有點怪異....)

回答

3

據我所知,關鍵必須是一個字符串,inte ger類型或Guid對象。基本上這會迫使你總是對每一個你想存儲的類都有一個人工鍵,但通常這是一個好主意。嘗試給ClassifiedRating一個整數密鑰,而不是嘗試使用類User

+0

是的,這是正確的,在數據​​庫中的PK必須在實際的列上,並且您的模型中的用戶屬性僅導航 – 2012-03-15 22:46:55

+0

謝謝,我不知道。它的工作原理,現在另一個錯誤的數字出來 – 2012-03-15 23:09:21

1

ClassifiedRating應該是這樣的:

public class ClassifiedRating 
{ 
    [Key, Column(Order = 0)] 
    public int RaterId { get; set; } 

    [Key, Column(Order = 1)] 
    public int ClassifiedId { get; set; } 

    public User Rater {get;set;} 
    public Classified Classified { get; set; } 

    public int rating { get; set; } 
} 

命名約定將檢測複合主鍵的兩個部分作爲一個外鍵,其他兩個表,你應該得到的兩個一一對多關係你需要在你的模型中。

+0

我將'虛擬'用於'用戶'和'分類'對象 – Jaider 2015-03-26 12:11:56