zoukankan      html  css  js  c++  java
  • 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; }        
        }

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

         

  • 相关阅读:
    程序自动网站留言,自动登录,自动投票等做法 httpclient 拂晓风起
    CruiseControl 安装 配置 教程 实例 搭建服务器 (CruiseControl + git/svn) 拂晓风起
    编码和字符集的关系 拂晓风起
    PuttyGen生成SSH(key) 带图 TortoiseGit和Github的SSH生成 拂晓风起
    计算时间差,将yyyyMMddHHmmss字符格式转为时间
    C# 操作非标准的xml文件
    SqlServer2000中调度包到作业中,自动执行失败的解决方法
    ReSharper 命名规则
    Js中setInterval、setTimeout不能传递参数问题 及各自的关闭方法
    获取存储过程返回值
  • 原文地址:https://www.cnblogs.com/zq8024/p/2605126.html
Copyright © 2011-2022 走看看