2

Given a EF-Code First CTP5 entity layout like:

public class Person 
{
     public List<Children> Childrens { get; set; }
}

and

public class Children
{
    public int Age { get; set; }
}

I want to do:

PersonQuery.Include(x => x.Childrens.OrderByDescending(child => child.Age).Take(3))

and get only 3 older childrens from list.

for example:

I got Person with 5 childrens ages 5, 10, 15, 20, 25

I want select the person + list of 3 childrens ages 25, 20, 15.

this is the error I have:

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

octavioccl
  • 35,665
  • 6
  • 76
  • 95
dor
  • 87
  • 9

1 Answers1

3

You can't do a query inside Include extension method to filter the related objects, you must specify only a navigation property or an expression to compose additional includes. Take a look this link (Remarks section) to see how you can use it.

You can filter related objects when you project your query using Select method:

var query=PersonQuery.Include(x => x.Children)
                     .Select(p=>new {PersonName=p.Name,
                                     Children=p.Children.OrderByDescending(child => child.Age).Take(3)});

If you want to know more about how to project Linq to Entities queries, then you should see this post.

Community
  • 1
  • 1
octavioccl
  • 35,665
  • 6
  • 76
  • 95