简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM