实体框架代码优先:关系约束中的从属角色和主要角色中的属性数必须相同

时间:2017-01-27 16:45:19

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

数据库构建错误:

  

在模型生成期间检测到一个或多个验证错误:

     

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

密钥类:


    [Table("Keys")]
    public class Key
    {
        [Key, Column(Order = 0)]
        public int Id { get; set; }

        [Key, Column(Order = 1)]
        public int OwnedByFId { get; set; }

        [Key, Column(Order = 2)]
        public int OwnedByUId { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        [ForeignKey("Id"), Column(Order = 1)]
        public virtual ICollection Authorities { get; set; }
    }

主管部门类:


    [Table("Key_Auths")]
    public class KeyAuthorities
    {
        [Key, Column(Order = 0)]
        public int Id { get; set; }

        [Key, Column(Order = 1)]
        public int KeyId { get; set; }

        public int DoorId { get; set; }

        public int VehicleId { get; set; }

        public int GateId { get; set; }
    }

问题:

我已经阅读了有关此问题的其他几个Stack Overflow问题,并尝试了一些东西,但我仍然无法弄清楚为什么这不能让我设置这个外键。

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

2 个答案:

答案 0 :(得分:0)

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

}

答案 1 :(得分:0)

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

你必须在你的外国课上设置所有的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")]