Entity Framework关系映射容易出错的地方
1. 一对一关联中, 主端必须配置成Required,且类上必须用Table修饰,才能让两个类保存到同一个表中, 依赖类中主键不需要与主端的类一样,但是必须映射到同一列,同时在DbContext主端的类必须在依赖类的前面出现(下面例子中的Role必须要放在RoleProfile定义的前面)。
[Table("WF_Role")]
public class Role
{
[Key]
public int RoleId { get; set; }
public string RoleName { get; set; }
[Required]
public RoleProfile Profile { get; set; }
}
[Table("WF_Role")]
public class RoleProfile
{
[Key, ForeignKey("MyRole"), Column("RoleId")]
public int Id { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
public Role MyRole { get; set; }
}
2. 两个类中有多个关系时,ForeignKey要用在关联的属性上,不能用在保存到数据库的字段上,另外有一个字段要设置成可空类型,否则会提示出错
[Table("WF_User")]
public class User
{
public int UserId { get; set; }
[MaxLength(50)]
public string UserName { get; set; }
public DateTime Birthday { get; set; }
public int Age { get; set; }
[Column("PRole")]
public int RoleId { get; set; }
[InverseProperty("PrimaryRoleForUsers")]
[ForeignKey("RoleId")]
public Role PrimaryRole { get; set; }
public int? SecondRoleId { get; set; }
[InverseProperty("SecondRoleForUsers")]
[ForeignKey("SecondRoleId")]
public Role SecondRole { get; set; }
}
[Table("WF_Role")]
public class Role
{
[Key]
public int RoleId { get; set; }
public string RoleName { get; set; }
public List<User> PrimaryRoleForUsers { get; set; }
public List<User> SecondRoleForUsers { get; set; }
}
public class User
{
public int UserId { get; set; }
[MaxLength(50)]
public string UserName { get; set; }
public DateTime Birthday { get; set; }
public int Age { get; set; }
[Column("PRole")]
public int RoleId { get; set; }
[InverseProperty("PrimaryRoleForUsers")]
[ForeignKey("RoleId")]
public Role PrimaryRole { get; set; }
public int? SecondRoleId { get; set; }
[InverseProperty("SecondRoleForUsers")]
[ForeignKey("SecondRoleId")]
public Role SecondRole { get; set; }
}
[Table("WF_Role")]
public class Role
{
[Key]
public int RoleId { get; set; }
public string RoleName { get; set; }
public List<User> PrimaryRoleForUsers { get; set; }
public List<User> SecondRoleForUsers { get; set; }
}
大家可否分享一下容易出错的地方?