• 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; }        
        }

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

         

  • 相关阅读:
    半主机模式和_MICROLIB 库
    工作中常用的git命令
    Mybatis延迟加载参数配置
    JUnit展示图形化测试结果
    可读、可维护、可扩展,原则、模式与重构
    乐观锁和悲观锁
    HashMap实现原理和底层数据结构?
    视图有啥用?
    单例模式常见有哪几种?
    RPC服务和HTTP服务的区别
  • 原文地址:https://www.cnblogs.com/zq8024/p/2605126.html
Copyright © 2020-2023  润新知