2017-06-20 115 views
1

所以我想如下創建一個簡單的產品 - 預覽1對1的關係:EF代碼首先不是一個外鍵設置爲一個關係

public class Product : BaseEntity 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   
    public Guid Id { get; set; } 
    public string name { get; set; } 
    public virtual EPS eps { get; set; } 
    public virtual Preview preview { get; set; } 

    [ForeignKey("userId")] 
    public virtual User user { get; set; } 
    public Guid userId { get; set; } 

} 

public class Preview : BaseEntity 
{ 
    [Key,ForeignKey("Product")]   
    public Guid Id { get; set; } 
    public string imagePath { get; set; } 
    public double width { get; set; } 
    public double height { get; set; } 
    public virtual List<TextPreview> Texts { get; set; } 
    public virtual List<ImagePlaceHolder> ImagePlaceHolders { get; set; } 
    [ForeignKey("ProductId")] 
    public virtual Product Product { get; set; } 
    public virtual Guid ProductId { get; set; } 
} 

我期待在預覽表中有一個外鍵,它將指向一個產品 ,但在運行遷移後,我將它作爲常規字段

enter image description here

我做錯了什麼?

回答

0

你幾乎有它,你只是錯過了一個一塊拼圖......

[ForeignKey("ProductId")] 
public virtual Product Product { get; set; } 

您還需要添加...

public Guid ProductId { get; set; } 

到預覽對象。

還值得注意的是,ForeignKey attrib可以放在任何一個屬性上,而字符串必須指向另一個。

由於它正在寫入,因此您正試圖使Id屬性爲相關表上的主鍵和外鍵指定值。

因此,最終的代碼可能看起來像......

public class Product : BaseEntity 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   
    public Guid Id { get; set; } 
    [ForeignKey("User")] 
    public Guid UserId { get; set; } 
    public string name { get; set; } 

    public virtual EPS eps { get; set; } 
    public virtual Preview preview { get; set; } 
    public virtual User user { get; set; } 
} 

public class Preview : BaseEntity 
{ 
    [Key]   
    public Guid Id { get; set; } 

    [ForeignKey("Product")] 
    public Guid ProductId { get; set; } 

    public string imagePath { get; set; } 
    public double width { get; set; } 
    public double height { get; set; } 

    public virtual List<TextPreview> Texts { get; set; } 
    public virtual List<ImagePlaceHolder> ImagePlaceHolders { get; set; } 

    public virtual Product Product { get; set; } 
} 

作爲一個方面說明我還建議不要使用像List<T>具體集合類型,而不是使用像IList<T>ICollection<T>它促進更好的代碼重用和可擴展性。

+0

感謝您的幫助,但是如果我遵循您的建議,最終會出現此錯誤:多重性在「Preview_product」關係中的'Preview_product_Source'角色中無效。因爲「依賴角色」屬性不是關鍵屬性,所以「依賴角色」的多重性的上界必須爲「*」。 –

+0

這就是這個問題解決,你現在有一個不同的問題,這裏解釋這裏... https://stackoverflow.com/questions/9292738/entity-framework-4-0-error-113-multiplicity-is-not-valid在角色 – War

+0

基本上你有1對1的關係,它似乎可能是問題,你想要的是一個0-1到1的關係...使guid ProductId可爲空「Guid?」可以解決這個問題 – War