Person是包含所有用户的用户模型。更改模型包括EngineerId和ManagerId,两者都是Person ID。为什么我会收到此错误?
无法在ProjectName.Models.Change类型上确定外键的复合外键排序。在复合外键属性上使用ForeignKey数据注释时,请确保使用Column data annotation或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; }
}
答案 0 :(得分:11)
您有2个外键属性(EngineerId
和ManagerId
)已与相同的导航属性(ForeignKey
关联(通过person
属性) 。通过这种方式,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; }
}