简体   繁体   中英

How do I specify a one to one relationship in Entity Framework Core where both sides have a foreign key to each other?

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.

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

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

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