[英]How to setup two foreign keys to the same parent column (Entity Framework)
I'm using ASP.NET MVC and I have the following class models 我正在使用ASP.NET MVC,并且具有以下类模型
Position: 位置:
public enum PosType
{
ICC, FP
}
public class Position
{
public int Id { get; set; }
public string Name { get; set; }
public PosType? PosType { get; set; }
}
Staff: 员工:
public class Staff
{
public int Id { get; set; }
public string StaffName { get; set; }
//FK to Position
public int PositionId { get; set; }
//Navigation property
public virtual Position Position { get; set; }
Member: 会员:
public class Member
{
public int Id { get; set; }
public string MemberName { get; set; }
//FK to Staff model which stores the ICC Staff Type value
public int? StaffId { get; set; }
//FK to Staff model which stores the FP Staff Type value
public int? FPNumber { get; set; }
//Navigation property
public virtual Staff Staff { get; set; }
On the Member model the StaffId
property is a foreign key to the Staff
model which is a pretty straight forward approach. 在Member模型上,
StaffId
属性是Staff
模型的外键,这是一种非常简单的方法。 The issue I'm having is how to handle the FPnumber
property since I would like it to be a foreign key to the Staff
model as well. 我遇到的问题是如何处理
FPnumber
属性,因为我也希望它也是Staff
模型的外键。 My overall goal is have the Member.StaffId
property store ICC staff type and the Member.FPNumber
property store FP staff type. 我的总体目标是拥有
Member.StaffId
属性存储库ICC人员类型和Member.FPNumber
属性存储库FP人员类型。 I tried adding the ForeignKey
attribute to the FPNumber
property, but it did not work since the StaffId
got removed from the Member table. 我尝试将
ForeignKey
属性添加到FPNumber
属性中,但是由于从Member表中删除了StaffId
所以该方法StaffId
。 Any other suggestions? 还有其他建议吗?
This should do the trick 这应该可以解决问题
public class Member
{
public int Id { get; set; }
public string MemberName { get; set; }
//FK to Staff model which stores the ICC Staff Type value
[ForeignKey("Staff")]
public int? StaffId { get; set; }
//FK to Staff model which stores the FP Staff Type value
[ForeignKey("FPStaff")]
public int? FPNumber { get; set; }
//Navigation property
public virtual Staff Staff { get; set; } //Use a better descriptive Name than Staff
public virtual Staff FPStaff{ get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.