Repository navigation
Description
Entity Framework is generating a composite ORDER BY clause when a query on one entity .Includes() an entity under a one-to-many relation and that related entity is loaded in the SELECT clause. The order by clause includes the primary keys of every single entity in the query as a whole, not just those under that relation. None of this happens if the relation is on a *-to-one relation. I haven't tested many-to-many.
This in combination with the change in EF 3.0 to utilize joins instead of multiple selects can have severe negative performance implications for queries with .Include() calls that worked well enough prior to EF 3.0. Not only does that mean there's extra load on the database server to do these orderings - the sql generated by EF 3.1 for one of our large queries executes in two minutes with the ORDER BY clause and 30 seconds without it - but also the database server isn't able to even start streaming results until it more or less has all the results assembled, leading to client-side timeouts.
I'm not sure if this is a bug or just undesirable behavior. I've found nothing documenting this on pages like https://docs.microsoft.com/en-us/ef/core/querying/related-data, and I've found no clear way to disable it or get around it, absent rewriting these queries or doing something ugly with a command interceptor, but I could have just missed a source of information. I totally understand the pivot to joins implies some things need to be rewritten, but this ORDER BY especially on every entity is excessive and mandates us to manually fine tune data loading where we were previously able to rely on EF for it, even when joins alone are fine.
Solutions in order of preference:
- Don't introduce these order by clauses unless asked for in the query
- Document this and provide some way to opt out of this behavior on a global or per-query basis.
- Document this and don't order by other entitles' keys outside the one-to-many-relation
- Document this behavior loudly and provide best practices to work around it
Steps to reproduce
See my gist with code and comments at https://gist.github.com/cwhitelaw/df7d12778966e16e0119a4ffce0a06dc?ts=4
Model:
public class MainEntity
{
public int Id { get; set; }
public int SingleRelatedEntityId { get; set; }
public SingleRelatedEntity SingleRelatedEntity { get; set; }
public List<ManyRelatedEntity> ManyRelatedEntities { get; set; }
}
public class SingleRelatedEntity
{
public int Id { get; set; }
}
public class ManyRelatedEntity
{
public int Id { get; set; }
public int MainEntityId { get; set; }
public MainEntity MainEntity { get; set; }
}
Output (the problem manifests in the queries labeled with main entities including to-many relation):
Query: main entities
SELECT [m].[Id], [m].[SingleRelatedEntityId]
FROM [MainEntities] AS [m]
Query: single-related entities
SELECT [s].[Id]
FROM [SingleRelatedEntities] AS [s]
Query: many-related entities
SELECT [m].[Id], [m].[MainEntityId]
FROM [ManyRelatedEntities] AS [m]
Query: main entities including to-one relation
SELECT [m].[Id], [m].[SingleRelatedEntityId], [s].[Id]
FROM [MainEntities] AS [m]
INNER JOIN [SingleRelatedEntities] AS [s] ON [m].[SingleRelatedEntityId] = [s].[Id]
Query: main entities including to-many relation
SELECT [m].[Id], [m].[SingleRelatedEntityId], [m0].[Id], [m0].[MainEntityId]
FROM [MainEntities] AS [m]
LEFT JOIN [ManyRelatedEntities] AS [m0] ON [m].[Id] = [m0].[MainEntityId]
ORDER BY [m].[Id], [m0].[Id]
Query: main entities including to-many relation, order by MainEntity.Id descending
SELECT [m].[Id], [m].[SingleRelatedEntityId], [m0].[Id], [m0].[MainEntityId]
FROM [MainEntities] AS [m]
LEFT JOIN [ManyRelatedEntities] AS [m0] ON [m].[Id] = [m0].[MainEntityId]
ORDER BY [m].[Id] DESC, [m0].[Id]
Query: main entities including both to-one and to-many relation
SELECT [m].[Id], [m].[SingleRelatedEntityId], [s].[Id], [m0].[Id], [m0].[MainEntityId]
FROM [MainEntities] AS [m]
INNER JOIN [SingleRelatedEntities] AS [s] ON [m].[SingleRelatedEntityId] = [s].[Id]
LEFT JOIN [ManyRelatedEntities] AS [m0] ON [m].[Id] = [m0].[MainEntityId]
ORDER BY [m].[Id], [s].[Id], [m0].[Id]
Query: many-related entities through MainEntity relation
SELECT [m0].[Id], [m0].[MainEntityId]
FROM [MainEntities] AS [m]
INNER JOIN [ManyRelatedEntities] AS [m0] ON [m].[Id] = [m0].[MainEntityId]
Query: many-related entities including their MainEntity
SELECT [m].[Id], [m].[MainEntityId], [m0].[Id], [m0].[SingleRelatedEntityId]
FROM [ManyRelatedEntities] AS [m]
INNER JOIN [MainEntities] AS [m0] ON [m].[MainEntityId] = [m0].[Id]
Further technical details
EF Core version: 3.1.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer 3.1.0
Target framework: .NET Core 3.1
Operating system: Windows 10 x64
IDE: Visual Studio 2019
Activity
ajcvickers commentedon Jan 13, 2020
@roji @maumar Any thoughts on this?
roji commentedon Jan 13, 2020
I remember doing some performance tests on ordering by primary keys some time ago (on PostgreSQL), and definitely did not see any difference close to 2 minutes vs. 30 seconds - but we should definitely look into this. I can do a quick perf investigation here.
@CWhitelaw this isn't exactly my domain, but to give some context... The ORDER By clause is added when materializing 1-to-many relations, so that the principal is grouped together while loading the dependent. If we don't have this, rows come at totally random order, and we must track all principals and look them up again on for each row. Having said that, if the ORDER BY necessarily triggers such a perf degradation I definitely agree we should re-examine this.
roji commentedon Jan 13, 2020
That's a good observation and we've raised this internally - it seems like the last dependent entity does not need necessarily need an ORDER BY on its primary key.
However, from the rest of your comment, it seems like the performance degradation you're experiencing could be completely unrelated to the ORDER BY clauses, but rather a case of eager loading being done with a single query. In a nutshell, versions before 3.0 sent a separate query for each related entity, where since 3.0 EF Core always generates a single query - which can cause a so-called "cartesian explosion" if too many joins are present. There are ways to rewrite your query to return to the pre-3.0 multiple query mechanism: please see this comment.
For now I'm going to assume that any perf issue here is related to the single-query issue, rather than to the ORDER BY clause - could you please take a look and confirm?
roji commentedon Jan 13, 2020
So to be sure I understand - can you please confirm you're seeing a 30s -> 2min difference on a single-join query (e.g. the query tagged "main entities including to-many relation" above), predicated solely on the existence or absence of the ORDER BY clause? If so, I'll definitely look into this.
roji commentedon Jan 13, 2020
Thanks, I'll look into this and will get back to you soon if I have any questions.
roji commentedon Jan 13, 2020
Thanks for the added info, it's important to know that the degradation is (for now) seen on a query with 8 includes/joins. This also means that you may be able to work around the issue here by breaking the query into separate parts as described in #18022.
Out of curiosity, if E8 seems to be the cause of the issue, do you have the same problem when removing the entire first include chain (i.e. E2-E7)?
Also, is there any chance you can provide your (minimal!) model, with an idea of the data required to reproduce this? Also, any chance you could check if this occurs on a regular, on-premise SQL Server instance rather than Azure?
I think it would be good to get to the bottom of this even though not ordering on the dependent side here may mitigate the issue you're specifically seeing.
roji commentedon Jan 13, 2020
Also, if you could post the specific SQL being generated that could be helpful.
15 remaining items
roji commentedon Feb 26, 2020
Opened #20076 to track the removal of ORDER BY for buffered tracked queries. Between that, #19828 (remove last ORDER BY) and #18022 ("easy API" to split queries), I don't think there's anything more to do here - am closing this issue.
@CWhitelaw at this point, the right thing to do is to manually split the query as described in #18022 (and to switch to the "easy API" once it's introduced). If, after splitting the query, you still encounter a scenario where an ORDER BY generates a significant perf degradation, please post a repro for that to #20076 - that would help us evaluate the necessity of doing that.
stijnherreman commentedon Aug 6, 2025
For searchability reasons: this impacts keyless entity types and you may need to generate an artificial key instead.
For example: configure an artificial entity using
builder.HasNoKey()andbuilder.ToSqlQuery(...)with a one-to-one navigation property to a real entity, which in turn has a one-to-many navigation property. Accessing the one-to-many navigation property throws an exception, even though the keyless entity itself is not relevant in theJOIN.#29788 is probably the same kind of issue as I described here.
roji commentedon Mar 9, 2026
Note that #29182 removes ORDER BYs for reference joins (to-one).