2014-10-20 51 views
0

我發佈了一個非常奇怪的場景,首先使用現有的數據庫和asp.net身份實體框架的代碼。我有一個簡單的模型USERPROFILEE.F 6.0代碼優先一對一導航屬性異常

[Table("CSUserProfile")] 
    public partial class UserProfile 
    { 
     [Key] 
     public string Id { get; set; } 

     [Required] 
     [Display(Name = "FirstName")] 
     public string FirstName { get; set; } 

     [Required] 
     [Display(Name = "LastName")] 
     public string LastName { get; set; } 

     [Required] 
     [Display(Name = "Phone")] 
     public string Phone { get; set; } 

     [Required] 
     public string Email { get; set; } 

     [Required] 
     [Display(Name = "Location")] 
     public string Location { get; set; } 

     [Required] 
     [Display(Name = "HomeTown")] 
     public string Hometown { get; set; } 

     public byte[] BlobData { get; set; } 

     [ForeignKey("fPersonLinkGID")] 
     public virtual List<ProfilePic> ProfilePic { get; set; } 
    }  

和圖像資料相片

[Table("CSProfilePic")] 
public partial class ProfilePic 
{ 
    [Key] 
    public Guid? GID { get; set; } 
    public string fPersonLinkGID { get; set; } 
    public byte[] BlobData { get; set; } 
} 

外鍵是fPersonLinkGID。一切工作正常,但我的問題是,如果我想用戶配置文件和這樣的圖像之間的一對一的關係

public virtual ProfilePic ProfilePic {get;組; }

(這是正確的情況下),我得到這個奇怪的例外:

的ForeignKeyAttribute財產「ProfilePic」上鍵入「eUni.Model.Application.UserProfile」是無效的。在依賴類型'eUni.Model.Application.UserProfile'上未找到外鍵名'fPersonLinkGID'。名稱值應該是逗號分隔的外鍵屬性名稱列表。

我不明白爲什麼我收到這個異常

+0

在EF中,對於一對一的關係,鍵必須是相同的類型。那是你的ProfilePic必須有一個Int作爲鍵。對於userId = x,您將擁有profilPicId = x。 – tschmit007 2014-10-20 08:58:42

+0

關鍵字是相同類型(字符串,字符串)使用一對多關係沒有問題。我的問題發生在一對一 – Antho 2014-10-20 09:02:58

+0

的PK必須是相同的類型:GUID與String不一樣。您可能需要使用相同的名稱。在用戶配置 – tschmit007 2014-10-20 09:08:31

回答

1

您可以閱讀this answer。它介紹瞭如何通過HasRequiredWithOptional來配置一對一關係。

至於我,我會通過以下方式創建一對一的關係。

public class Store { 
    [Key] 
    public long Id { get; set; } 

    public virtual Item TheItem { get; set; } 

    // .... 
} 

public class Item { 
    // It is FK, and also PK. 
    [Key, ForeignKey("TheStore")] 
    public long Id { get; set; } 

    // The same string in the ForeignKey attribute. Ex: ForeignKey("TheStore") 
    public virtual Store TheStore { get; set; } 

    // .... 
} 
相關問題