Linq中的.Include().Where().Select()到实体查询 [英] .Include() .Where() .Select() in Linq to Entities Query
问题描述
我有一个Linq查询,查询以下表:具有一对多链接的任务:TaskLinks和TaskLinks有一对一链接到名为Entities的表.
I have a Linq query that queries the following tables: Tasks with a one-to-many link to: TaskLinks and TaskLinks has a one-to-one link to a Table called Entities.
我正在尝试选择任务,希望(通过.include)加载任务链接,然后选择链接到任务链接的实体.但是我需要过滤任务(按访问级别int)和任务链接,以便不包括任何非活动(布尔)记录.
I am trying to select the task, eager load (via .Include) the TaskLinks and select the Entity linked to the TaskLink. But I need to filter the Task (by Access Level int) and the TaskLinks so that I don't include any Inactive (bool) records.
这是我的Linq查询:
Here is my Linq query:
Tasks.Where(t => t.AccessLevel <= 5)
.Include(tl => tl.TaskLinks.Where(tl2=> tl2.IfInactive == false)
.Select(tls => tls.Entity))
我在LinqPad中运行此查询,但出现以下我不理解的错误:
I run this query in LinqPad, and I get the following error which I do not understand:
ArgumentException:包含路径表达式必须引用在类型上定义的导航属性.使用虚线路径作为参考导航属性,并使用选择"运算符作为集合导航属性. 参数名称:路径
ArgumentException: The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path
如何重新编写此查询,以便筛选出包含的任务链接,然后选择实体?
How can I re-write this query so I can filter the Included TaskLinks, and select the Entity?
先谢谢您!
鲍勃
推荐答案
.Include(...)
向查询提供程序建议"以急于加载导航属性.在这种情况下,它不会这样做b/c您的结果不是Task
实体,而是Entity
实体.
.Include(...)
'suggests' to the query provider to eager load the navigation property. In this case, it won't do so b/c your results are not Task
entities, they're Entity
entities.
无论如何,您都不会在include语句中过滤集合导航属性(这是导致您出错的原因).
In any case, you don't filter a collection navigation property in an include statement (which is what's causing your error).
您需要以下内容:
// start with Tasks, filter by AccessLevel
Tasks.Where( t => t.AccessLevel <= 5 )
// get the TaskLinks for each Task
.SelectMany( t => t.TaskLinks )
// filter TaskLinks by IfInactive == false
.Where( tl => !tl.IfInactive )
// update to keep the hierarchy you want
.GroupBy( tl => tl.Task )
.Select( g => new
{
Task = g.Key,
FilteredTaskLists = g.Select( tl => new
{
TaskList = tl,
Entity = tl.Entity
} )
} );
这篇关于Linq中的.Include().Where().Select()到实体查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!