var result = ParentTable.Set
.Include("Children")
.Include("Children.GrandChildren")
.SelectMany(p=>p.Children)
.Where(c=>c.GrandChildren.Any(whatever))
将返回 null,即使
var result = ParentTable.Set
.Include("Children")
.Include("Children.GrandChildren")
里面有完全填充的数据。
需要做的
var result = ParentTable.Set
.SelectMany(p=>p.Children)
.Include("GrandChildren")
.Where(c=>c.GrandChildren.Any(whatever))
这个例子有点做作,但我在一个更大更复杂的查询中遇到了这个问题,其中子选择投影使用 SelectMany 将计数填充到特定属性中,其他数据被投影到其他属性中在 selectMany 之外,这些属性正在填充,但 selectmany 计数没有。查询的不同部分如何延迟加载同一数据的不同部分,这让人非常困惑!
最佳答案
您应该使用 ThenInclude
来获取子项。
我会将您的查询重写为:
var result = ParentTable.Set
.Include(p => p.Children)
.ThenInclude(c => c.GrandChildren.Where(gc => gc.whatver))
.SelectMany(p => p.Children)
关于c# - 为什么 LINQ SelectMany 忽略包含? (实际上删除了加载的数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39731930/