Why the Left Outer join?

后端 未结 3 1923
醉梦人生
醉梦人生 2021-02-20 04:03

weird one. (Probably not weird, at all)

I have 3 objects, Employee, Rota and Department.

public class Employee
{
    public int Id { get; set; }
    publ         


        
3条回答
  •  日久生厌
    2021-02-20 04:43

    The reason is incorrect mapping. It looks correct but it is not. Use these instead:

    internal class EmployeeMapping : EntityTypeConfiguration
    {
        public EmployeeMapping()
        {
            HasKey(a => a.Id);
            Property(a => a.Id).HasColumnName("UserId");
    
            HasRequired(a => a.Department).WithMany()
                                                      .Map(a => a.MapKey("DepartmentId"));
        }
    }
    
    internal class RotaMapping : EntityTypeConfiguration
    {
        public RotaMapping()
        {
            HasKey(a => a.Id);
            Property(a => a.Id).HasColumnName("RotaId");
    
            HasOptional(a => a.Employee).WithMany()
                                                  .Map(a => a.MapKey("EmployeeId"));
            HasOptional(a => a.Department).WithMany()
                                                      .Map(a => a.MapKey("DepartmentId"));
        }
    }
    

    Your mapping is correctly interpreted when creating database and database looks correct but EF thinks that you map all relations as one-to-one. That confuse EF and it will generate queries used for one-to-one to create internal entity references. These left joins are necessary for one-to-one relation when you tell EF that dependent entities are optional - EF doesn't know if they exist unless it loads their keys.

提交回复
热议问题