All the documentation I'm finding on one to one relationships in Entity Framework talk about one side being the dependent and only having a foreign key in one table. How can I tell Entity Framework that both tables have a foreign key to each other. Here is a simple example:
public class TechnicalAdvisor
{
public Guid TechnicalAdvisorId { get; set; }
public Guid ProjectRequestId { get; set; }
public virtual ProjectRequest ProjectRequest { get; set; }
}
public class ProjectRequest
{
public Guid ProjectRequestId { get; set; }
public Guid? TechnicalReviewCompletedById { get; set; }
public virtual TechnicalAdvisor TechnicalReviewCompletedBy { get; set; }
}
The use case is we have a project request that requires technical review. The TechnicalAdvisor
table is a whitelist basically for who can do it. Then we need an id for who actually did it. I can't figure out how to tell Entity Framework what this relationship is.
CodePudding user response:
You're almost there. You just need an additional table to represent the TechincalAdvisor
s who are on the Whitelist
.
public class TechnicalAdvisorWhitelist
{
public int Id {get; set;}
public Guid TechnicalAdvisorId {get; set;}
}
CodePudding user response:
So I was seeing this wrong. Really I had two relationships: 1:0/1 and 1:many so really the answer is this:
modelBuilder.Entity<TechnicalAdvisor>()
.HasOne(x => x.ProjectRequest)
.WithMany()
.HasForeignKey("ProjectRequestId");
modelBuilder.Entity<ProjectRequest>()
.HasOne(x => x.TechnicalReviewCompletedBy)
.WithOne()
.HasForeignKey<ProjectRequest>(x => x.TechnicalReviewCompletedById);