2013-02-22 30 views
0

我有實體:不能得到一對一的相關對象

public class User 
    { 
     public int UserId { get; set; } 
     public string UserName { get; set; } 
     public string Email { get; set; } 
     ... 
     public virtual Profile Profile { get; set; } 
     ... 
public class Profile 
    { 
     public int UserId { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 

當我試圖讓用戶我得到錯誤:

System.Data.Edm.EdmEntityType: : EntityType 'Profile' has no key defined. Define the key for this EntityType. 

當我改變實體:

public class User 
    { 
     [Key] 
     public int UserId { get; set; } 
     public string UserName { get; set; } 
     public string Email { get; set; } 
     ... 
     public virtual Profile Profile { get; set; } 
     ... 
public class Profile 
    { 
     [Key] 
     public int UserId { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 

我收到錯誤:

{"Invalid column name 'Profile_UserId'."} 

我在做什麼錯?
enter image description here

回答

1

根據http://blog.bennymichielsen.be/2011/06/02/entity-framework-4-1-one-to-one-mapping/它可以工作:

public class User 
{ 
     [Key] 
     public int UserId { get; set; } 
     public string UserName { get; set; } 
     public string Email { get; set; } 
     public virtual Profile Profile { get; set; } 
} 

public class Profile 
{ 
     [Key] 
     public int UserId { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     [Required] 
     public virtual User User { get; set;} 
} 
+0

現在,我得到'無效的列名稱ProfileID'.'我更新的問題添加我的數據庫圖。爲什麼從'Profile'中刪除'UserId'並添加'Id'? – 1110 2013-02-22 21:23:20

+0

我認爲這是代碼優先的方法。現有的數據庫結構會比較困難,但是您可以嘗試在Profile屬性中設置'[ForeignKey(「UserId」)]'並將列重命名爲UserId? – MarcinJuraszek 2013-02-22 21:26:19

+0

我試過了,我得到:'在模型生成過程中檢測到一個或多個驗證錯誤: \t System.Data.Edm.EdmAssociationEnd::多重性在'User_Profile'關係中的'User_Profile_Source'角色中無效。因爲依賴角色是指關鍵屬性,因此角色的多樣性的上限必須是 1 .' – 1110 2013-02-22 21:29:39

相關問題