EF之外键Include() left join

项目中用EF实现外键查询出的数据, 查询数量正确, 但实现返回数据集数量不对

//DbContext.cs
HasRequired(s => s.ClassRoom)
            .WithMany()
            .HasForeignKey(student => student.ClassRoomId);
//查询语句
dbRead.Set<Student>().Include(x=>x.ClassRoom);

查询 .Count()和.ToList()结果数量不一致

经调试后发现生成的Sql语句为 inner join

正确的结果应该是 left join

此时应该如下定义外键

HasOptional(s => s.ClassRoom)
             .WithMany()
             .HasForeignKey(student => student.ClassRoomId);

此时返回的结果就正确了!

原文地址:https://www.cnblogs.com/hanf/p/6089303.html