Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by child table in entity framework

In my Linq I access a simple master/detail table:

_db.Countries.Include(x=>x.People);

I wish the People to be sorted by Lastname, but when I include a order by in the include it errors out with :

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
like image 371
Ian Vink Avatar asked Oct 14 '25 02:10

Ian Vink


2 Answers

You can do this.

var countries = _db.Countries
   .Select(c => new 
   {
       Country = c,
       People = c.People.OrderBy(p => p.Lastname)
   })
   .AsEnumerable() // not execute yet
   .Select(a => a.Country)
   .ToArray(); // execute

Even though Select only selects the Country, the People in anonymous type will connect to People property on each Country.

The generated sql will include the order by query like.

ORDER BY [Project1].[Id] ASC, [Project1].[C1] ASC, [Project1].[Lastname] ASC

PS

As work around of eager loading, what you can do is doing relationship fix-up. There will only one database roundtrip using this approach instead of loading all countries first then load each people.

Relationship Fix-up is the process by which the EF, links related Entities together. For example fix-up will set the "Customer" property of an Order when a known to be related Customer is materialized from the database. Once you understand fix-up you can leverage it to do all sorts of interesting things. - Entity Framework Jargon by Alex D James

like image 140
Yuliam Chandra Avatar answered Oct 16 '25 20:10

Yuliam Chandra


This is not supported. You could order the child collections on the client once the query is executed by looping through the countries collection retrieved from the database and ordering its People property.

like image 41
Darin Dimitrov Avatar answered Oct 16 '25 20:10

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!