在模型生成期间检测到一个或多个验证错误:
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
答案 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:Id
、OwnedByFId
和 OwnedByUId
)唯一标识,但是您的尝试仅使用 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")]
。