【问题标题】:How to setup two foreign keys to the same parent column (Entity Framework)如何为同一个父列设置两个外键(实体框架)
【发布时间】:2019-01-22 18:55:33
【问题描述】:

我正在使用 ASP.NET MVC,并且我有以下类模型

职位:

public enum PosType
{
    ICC, FP
}

public class Position
{
    public int Id { get; set; }
    public string Name { get; set; }
    public PosType? PosType { get; set; }
}

员工:

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; }

会员:

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; }

在成员模型上,StaffId 属性是 Staff 模型的外键,这是一种非常直接的方法。我遇到的问题是如何处理 FPnumber 属性,因为我希望它也成为 Staff 模型的外键。我的总体目标是拥有Member.StaffId property store ICC 员工类型和Member.FPNumber property store FP 员工类型。我尝试将ForeignKey 属性添加到FPNumber 属性,但由于StaffId 从成员表中删除,它不起作用。还有其他建议吗?

【问题讨论】:

标签: c# entity-framework


【解决方案1】:

这应该可以解决问题

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; }
}

【讨论】:

  • 我还建议更准确地重命名“Staff”成员。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
相关资源
最近更新 更多