OrderBy doesn't work if ThenInclude uses (or how to order nested collection)
See original GitHub issueSteps to reproduce
There is no docs found about ordering nested collection (ThenInclude() should be used), but found some fresh samples which should work (based on discussion).
Hence using the same approach the following code should sort nested items, but it doesn’t (no exception thrown):
var res = _db.Set<ApplicationUser>()
.OrderBy(u => u.Blogs.OrderBy(b => b.Posts.OrderBy(p => p.PostOrder).First().PostOrder))
.Include(u => u.Blogs)
.ThenInclude(b => b.Posts)
.Single(u => u.Id == userId);
Further technical details
EF Core version: 1.1.2 Database Provider: Doesn’t work on both Microsoft.EntityFrameworkCore.SqlServer and Npgsql.EntityFrameworkCore.PostgreSQL (this is the main one) Operating system: Windows 7 / Mac OS X 10.12.6 IDE: VS Code / Visual Studio 2017
Issue Analytics
- State:
- Created 6 years ago
- Comments:8 (5 by maintainers)
Top Results From Across the Web
OrderBy in Include child using EF Core [duplicate]
When I retrieve an instance, I need the nested list to be ordered by one of the child's properties. What is the correct...
Read more >Eager Loading of Related Data - EF Core
When applying Include to load related data, you can add certain enumerable operations to the included collection navigation, which allows for ...
Read more >How to query nested object with grandchildren with EF Core
Hi! I have an example of querying a nested object var prod1 = context.Categories .Include(c => c.Products).FirstOrDefault()? .Products.
Read more >Querying in Entity Framework Core
Teachers) will load the Teacher collection property of the Grade entity. The ThenInclude method must be called after the Include method. The above...
Read more >Entity Framework Core 5 - Pitfalls To Avoid and Ideas to Try
In this post, we'll look at some pitfalls and ideas EF Core users like yourself may want to consider when developing an application....
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Include only determines which navigations are going to be loaded in the final projection. For your scenario you can try ordering on the client:
If you want to sort on the server, then you would have to construct the projection manually (i.e. Include can’t be used for this) - and this currently would produce a separate query to fetch Posts for each Blog (which is potentially very slow)
closing as Duplicate of #9067