.Include() .Where() .Select() in Linq to Entities Query

╄→гoц情女王★ 提交于 2020-01-14 11:51:22

问题


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.

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.

Here is my Linq query:

Tasks.Where(t => t.AccessLevel <= 5)
     .Include(tl => tl.TaskLinks.Where(tl2=> tl2.IfInactive == false)
     .Select(tls => tls.Entity))

I run this query in LinqPad, and I get the following error which I do not understand:

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?

Thank You in Advance!!

Bob


回答1:


.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.

In any case, you don't filter a collection navigation property in an include statement (which is what's causing your error).

You want the following:

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


来源:https://stackoverflow.com/questions/20334379/include-where-select-in-linq-to-entities-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!