首页 > 代码库 > EF之外键Include() left join

EF之外键Include() left join

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

//DbContext.csHasRequired(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);

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

EF之外键Include() left join