简体   繁体   中英

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

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

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.

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