问题描述
人员是包括所有用户的用户模型.更改模型包括EngineerId和ManagerId,它们都是Person ID.为什么会出现此错误?
Person is the user model that includes all users. The change model includes the EngineerId and the ManagerId, both are Person IDs. Why am I getting this error?
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; }
}
推荐答案
您具有两个关联的外键属性( EngineerId
和 ManagerId
)(通过 ForeignKey
属性),并具有相同的导航属性( person
).EF通过这种方式认为它们构成了一个复合密钥,因此您将获得异常.
You have 2 foreign key properties (EngineerId
and ManagerId
) that you have associated (via ForeignKey
attribute) with the one and the same navigation property (person
). This way EF thinks they form a composite key, hence the exception you are getting.
由于(如果我理解正确),您的意图是建立2个关系,因此需要将每个外键与单独的导航属性相关联.这是您需要更改的必要部分:
Since (if I understand correctly) your intent is to have 2 relationships, you need to associate each foreign key with a separate navigation property. Here is the essential part that you need to change:
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; }
}
这篇关于无法确定外键的复合外键顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!