无法确定外键的复合外键顺序

本文关键字:顺序 复合 无法确定 | 更新日期: 2023-09-27 18:13:35

Person是包含所有用户的用户模型。变更模型包括EngineerId和ManagerId,两者都是Person id。为什么会出现这个错误?

无法确定ProjectName.Models.Change类型上的外键的组合外键顺序。当在复合外键属性上使用ForeignKey数据注释时,确保使用Column数据注释或fluent API指定顺序。

public class Change
{
    [Key]
    public int ChangeId { get; set; }
    [Required(ErrorMessage = "Change description is required.")]
    [Display(Name = "Change Description")]
    [DataType(DataType.MultilineText)]
    public string ChangeDescription { get; set; }
    [Required(ErrorMessage = "Change date is required.")]
    [Display(Name = "Date of Change")]
    [DataType(DataType.Date)]
    public DateTime ChangeDate { get; set; }
    [Required(ErrorMessage = "Time is required.")]
    [Display(Name = "Time of Change")]
    [DataType(DataType.Time)]
    public DateTime ChangeTime { get; set; }
    [Required(ErrorMessage = "Engineer name is required.")]
    [Display(Name = "Engineer")]
    [ForeignKey("person")]
    public int EngineerId { get; set; }
    [Required(ErrorMessage = "Status is required.")]
    [Display(Name = "Status")]
    public int StatusId { get; set; }
    [Required(ErrorMessage = "Manager is required.")]
    [Display(Name = "Manager")]
    [ForeignKey("person")]
    public int ManagerId { get; set; }
    [Required(ErrorMessage = "System is required.")]
    [Display(Name = "System")]        
    public int SystemDetailId { get; set; }
    public virtual Person person { get; set; }
    public virtual Status status { get; set; }
    public virtual SystemDetail systemdetail { get; set; }
}

无法确定外键的复合外键顺序

您有2个外键属性(EngineerIdManagerId),您已与一个和相同的导航属性(person)相关联(通过ForeignKey属性)。这样EF就认为它们形成了一个组合键,因此你得到了异常。

既然(如果我理解正确的话)你的意图是有2个关系,你需要将每个外键与一个单独的导航属性相关联。以下是需要修改的关键部分:

public class Change
{
    // ...
    [Required(ErrorMessage = "Engineer name is required.")]
    [Display(Name = "Engineer")]
    [ForeignKey("Engineer")]
    public int EngineerId { get; set; }
    [Required(ErrorMessage = "Manager is required.")]
    [Display(Name = "Manager")]
    [ForeignKey("Manager")]
    public int ManagerId { get; set; }
    // instead of person property:
    public virtual Person Engineer { get; set; }
    public virtual Person Manager { get; set; }
}