【问题标题】:Entity Framework Code First: The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical实体框架代码优先:关系约束中的从属角色和主体角色中的属性数量必须相同
【发布时间】:2017-06-13 10:15:10
【问题描述】:

数据库构建错误:

在模型生成过程中检测到一个或多个验证错误:

Key_Authorities_Source_Key_Authorities_Target: : 数量 关系中的从属角色和主要角色中的属性 约束必须相同。

关键类:

[表(“键”)] 公共类密钥 { [键,列(顺序= 0)] 公共 int ID { 获取;放; } [键,列(顺序 = 1)] 公共 int OwnedByFId { 获取;放; } [键,列(顺序 = 2)] 公共 int OwnedByUId { 获取;放; } 公共字符串名称 { 获取;放; } 公共字符串描述 { 获取;放; } [ForeignKey("Id"), 列(Order = 1)] 公共虚拟 ICollection Authorities { 获取;放; } }

关键权限类:

[表(“Key_Auths”)] 公共类 KeyAuthorities { [键,列(顺序= 0)] 公共 int ID { 获取;放; } [键,列(顺序 = 1)] 公共 int KeyId { 获取;放; } 公共 int DoorId { 获取;放; } 公共 int VehicleId { 获取;放; } 公共 int GateId { 获取;放; } }

问题:

我已经阅读了有关此问题的其他几个堆栈溢出问题并尝试了很多东西,但我仍然无法弄清楚为什么这不允许我设置此外键。

我真的很感激一些帮助:c

【问题讨论】:

    标签: entity-framework foreign-keys foreign-key-relationship composite-primary-key


    【解决方案1】:

    错误消息实际上是告诉您 number 个属性不匹配。这是因为您的 Key 类由 3 个属性唯一标识(您定义的 3 个 PK:IdOwnedByFIdOwnedByUId),但您尝试定义一个外键您的 Key 类仅使用 Id

    你必须在你的外国班级上设置所有的PK:

    [Table("Key_Auths")]
    public class KeyAuthorities
    {
        [Key, Column(Order = 0)]
        public int Id { get; set; }
    
        [Key, Column(Order = 1)]
        [ForeignKey("Id, OwnedByFId, OwnedByUId")]
        public int KeyId { get; set; }
    
        public int DoorId { get; set; }
        
        public int VehicleId { get; set; }
    
        public int GateId { get; set; }
    }
    

    注意我添加了数据注释[ForeignKey("Id, OwnedByFId, OwnedByUId")]

    【讨论】:

      【解决方案2】:
      // error message is basically telling that you have 
      // not configured the keys and their order properly in "Keys" table
      
      public class Keys {
          [Key, Column(Order = 0)]
          public int Key_1 { get; set; }
      
          [Key, Column(Order = 1)]
          public int Key_2 { get; set; }
      
          // order is important here as defined in "KeyAuthorities" table
          [ForeignKey("KeyAuthorities", Column(Order = 0)]
          public int KeyAuthorities_Key_1 { get; set; }
      
          [ForeignKey("KeyAuthorities", Column(Order = 1)]
          public int KeyAuthorities_Key_2 { get; set; }
      
          public virtual ICollection KeyAuthorities { get; set; }
      }
      
      public class KeyAuthorities {
          [Key, Column(Order = 0)]
          public int KeyAuthorities_Key_1 { get; set; }
      
          [Key, Column(Order = 1)]
          public int KeyAuthorities_Key_2 { get; set; }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2012-07-30
        • 1970-01-01
        • 2013-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-31
        • 1970-01-01
        相关资源
        最近更新 更多