【发布时间】:2014-04-11 16:20:53
【问题描述】:
我有Parent 和Child 实体相互关联为1 到M。我需要在单个SQL 查询中同时查询孩子和父母,但Include 方法在某些情况下无法正常工作。
这对Parent 和Child 表(通过JOIN)进行了正确的单个查询:
var r1 =
ctx.Set<Parent>()
.Include(p => p.Childs)
.Where(p => p.Id == 1)
.ToList();
一旦我动态创建了一个匿名对象,孩子们就会迷路,SQL 只包含父母的字段。子项的检索仍然是惰性的 - 它们仍然没有加载:
var r2 =
ctx.Set<Parent>()
.Include(p => p.Childs)
.Where(p => p.Id == 2)
.Select(p => new { myParent = p})
.ToList();
问题:
- 为什么会这样?
- 如何在我的 LINQ 中构造一个新的匿名对象,这样孩子才不会迷路?
附言我想保留 Parent 虚拟的 Childs 属性。
【问题讨论】:
-
为什么需要创建匿名对象?一种解决方案是在选择
var r2 = ctx.Set<Parent>().Include(p => p.Childs).Where(p => p.Id == 2).ToList() /* or ToArray() or something which evealutes the query */.Select(p => new { myParent = p}).ToList();之前运行查询
标签: c# .net linq entity-framework