Setting up multiple Foreign keys of same class in .Net Core / EF Core

后端 未结 1 1798
闹比i
闹比i 2021-01-18 13:03

I\'m building a .Net Core web app to replace an old legacy Access ADP/ADE front end to a project management SQL Server database. However, the builder of the original DB didn

相关标签:
1条回答
  • 2021-01-18 13:50

    Yes, you need to have separate project collections.

    In Employee, you would have:

    public ICollection<Project> PmProjects { get; set; }
    public ICollection<Project> CadProjects { get; set; }
    public ICollection<Project> SalesProjects { get; set; }
    

    In Project, you would have:

    public Employee PmEmployee { get; set; }
    public Employee CadEmployee { get; set; }
    public Employee SalesRepEmployee { get; set; }
    

    The builder would be :

    modelBuilder.Entity<Project>(entity =>
    {
    // Fluent API for column properties
    ...
    entity.HasOne(d => d.PmEmployee)
        .WithMany(p => p.PmProjects)
        .HasForeignKey(d => d.PmEmployeeId)
        .OnDelete(DeleteBehavior.SetNull)
        .HasConstraintName("FK_Project_Employee_PM");
    
    entity.HasOne(d => d.CadEmployee)
        .WithMany(p => p.CadProjects)
        .HasForeignKey(d => d.CadEmployeeId)
        .OnDelete(DeleteBehavior.SetNull)
        .HasConstraintName("FK_Project_Employee_CAD");
    
     entity.HasOne(d => d.SalesRepEmployee)
        .WithMany(p => p.SalesProjects)
        .HasForeignKey(d => d.SalesRepEmployeeId)
        .OnDelete(DeleteBehavior.SetNull)
        .HasConstraintName("FK_Project_Employee_SALES");
     });
    
    0 讨论(0)
提交回复
热议问题