可以使用实体框架在另一个表中调用两次作为外键的主键吗?
Posted
技术标签:
【中文标题】可以使用实体框架在另一个表中调用两次作为外键的主键吗?【英文标题】:Can a primary key called twice in another table as foreign key using Entity Framework? 【发布时间】:2021-10-25 20:49:19 【问题描述】:如何在两列中使用主键作为另一个表的外键。
public class ResumeSharing
[Key]
public int ResumeSharingId get; set;
[ForeignKey("AppliedJobs")]
public int AppliedJobId get; set;
public virtual AppliedJob AppliedJobs get; set;
public bool OwnCompany get; set;
[Display(Name = "RecruiterFrom")]
public int RecruiterId get; set;
public virtual Recruiter Recruiters get; set;
[Display(Name = "RecruiterTo")]
public int RecruiterId get; set;
public virtual Recruiter Recruiters get; set;
[ForeignKey("Companies")]
public int CompanyId get; set;
public virtual Company Companies get; set;
public string SharedFiles get; set;
我想在此表中调用RecruiterId
两次。我该怎么做?
【问题讨论】:
调用主键是什么意思?你的意思是 reference 吗?就像在子表中存储两次一样? 【参考方案1】:你必须添加导航属性
public class ResumeSharing
[Key]
public int ResumeSharingId get; set;
[ForeignKey("AppliedJob")]
public int AppliedJobId get; set;
public virtual AppliedJob AppliedJob get; set;
public bool OwnCompany get; set;
[Display(Name = "RecruiterFrom")]
public int RecruiterFromId get; set;
[ForeignKey(nameof(RecruiterFromId))]
[InverseProperty("RecruiterFroms")]
public virtual Recruiter RecruiterFrom get; set;
[Display(Name = "RecruiterTo")]
public int RecruiterToId get; set;
[ForeignKey(nameof(RecruiterToId))]
[InverseProperty("RecruiterTos")]
public virtual Recruiter RecruiterTo get; set;
[ForeignKey("Company")]
public int CompanyId get; set;
public virtual Company Company get; set;
public string SharedFiles get; set;
public class Recruiter
[Key]
public int Id get; set;
[InverseProperty(nameof(ResumeSharing.RecruiterFrom))]
public virtual ICollection<Recruiter> RecruiterFroms get; set;
[InverseProperty(nameof(ResumeSharing.RecruiterTo))]
public virtual ICollection<Recruiter> RecruiterTos get; set;
【讨论】:
以上是关于可以使用实体框架在另一个表中调用两次作为外键的主键吗?的主要内容,如果未能解决你的问题,请参考以下文章