Entity Framework关系映射容易出错的地方

1. 一对一关联中, 主端必须配置成Required,且类上必须用Table修饰,才能让两个类保存到同一个表中, 依赖类中主键不需要与主端的类一样,但是必须映射到同一列,同时在DbContext主端的类必须在依赖类的前面出现(下面例子中的Role必须要放在RoleProfile定义的前面)。

     

    [Table("WF_Role")]  

    public class Role
    {
        [Key]
        public int RoleId { getset; }
 
        public string RoleName { getset; }
 
        [Required]
        public RoleProfile Profile { getset; }
    }

    [Table("WF_Role")]
    public class RoleProfile
    {
        [Key, ForeignKey("MyRole"), Column("RoleId")]
        public int  Id { getset; }
        public string Country { getset; }
        public string ZipCode { getset; }

        public Role MyRole { getset; }
    } 

 

 

 

 2. 两个类中有多个关系时,ForeignKey要用在关联的属性上,不能用在保存到数据库的字段上,另外有一个字段要设置成可空类型,否则会提示出错

 

    [Table("WF_User")]
    public class User
    {
        public int UserId { getset; }

        [MaxLength(50)]
        public string UserName { getset; }
        public DateTime Birthday { getset; }
        public int Age { getset; }           

        [Column("PRole")]
        public int RoleId { getset; }

        [InverseProperty("PrimaryRoleForUsers")]
        [ForeignKey("RoleId")]
        public Role PrimaryRole { getset; }
        
        public int? SecondRoleId { getset; }

        [InverseProperty("SecondRoleForUsers")]
        [ForeignKey("SecondRoleId")]
        public Role SecondRole { getset; }
    }

    [Table("WF_Role")]
    public class Role
    {        
        [Key]
        public int RoleId { getset; }
        public string RoleName { getset; }

        public List<User> PrimaryRoleForUsers { getset; }

        public List<User> SecondRoleForUsers { getset; }        
    }

 

 大家可否分享一下容易出错的地方?

     

 

 

 

posted @ 2012-07-23 16:24  Do you know, jack?  阅读(319)  评论(0编辑  收藏  举报