2013-02-22 29 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

相关问题