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

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

posted @ 2016-11-22 14:49  Hanf  阅读(1217)  评论(0编辑  收藏  举报
Copyright © 2008-2016 Hanf All Rights Reserved