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

c# entity-framework linq-to-entities sql

Question

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
4
12/2/2013 5:34:48 PM

Popular Answer

.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
                } )
        } );
2
12/2/2013 9:03:29 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow