简体   繁体   中英

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

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. 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. My overall goal is have the Member.StaffId property store ICC staff type and the Member.FPNumber property store FP staff type. I tried adding the ForeignKey attribute to the FPNumber property, but it did not work since the StaffId got removed from the Member table. 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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM