.Include()
are empty when using .Take()
I was having this bug when using .Include(x => x.Children)
and .Take()
of Entity Framework Core. The bug was that the child entities specified in the .Include()
statement are not included in the result of the query (see Children.Count = 0
in the image below):
But when I comment out the line .Take(input.Count)
, all of a sudden the children are included in the result of the query:
When I inspected the SQL query generated by EF Core, I got this message:
This LINQ query is being executed in split-query mode, and the SQL shown is for the first query to be executed. Additional queries may also be executed depending on the results of the first query.
I did more googling and found out the reason for the bug in the documentation for EF Core:
When using split queries with Skip/Take on EF versions prior to 10, pay special attention to making your query ordering fully unique; not doing so could cause incorrect data to be returned. For example, if results are ordered only by date, but there can be multiple results with the same date, then each one of the split queries could each get different results from the database. Ordering by both date and ID (or any other unique property or combination of properties) makes the ordering fully unique and avoids this problem. Note that relational databases do not apply any ordering by default, even on the primary key.
So the solution is to modify the .OrderBy()
expression so that the ordering in the query is unique. In my case, I used the Id
property of the parent entities for the ordering.
Problem solved.