dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.69k stars 3.17k forks source link

Inaccurate query warning about distinct operator after ordering with CROSS APPLY OPENJSON #33477

Closed DanielStout5 closed 5 months ago

DanielStout5 commented 6 months ago

File a bug

The "LogDistinctAfterOrderBy" warning is triggered for SQL that does not use a distinct after ordering

This is the generated SQL:

SELECT [t].[Value]
FROM (
    SELECT DISTINCT [o].[Value]
    FROM [cms].[Content] AS [c]
    CROSS APPLY OPENJSON(CAST([c].[Data] AS nvarchar(max)), N'$.SportType') AS [o]
) AS [t]
ORDER BY [t].[Value]

From what I can tell, the DISTINCT is applied before the ordering, not after.

Include verbose output

Microsoft.EntityFrameworkCore.Query The query uses the 'Distinct' operator after applying an ordering. If there are any row limiting operation used before 'Distinct' and after ordering then ordering will be used for it. Ordering(s) will be erased after 'Distinct' and results afterwards would be unordered.

Include provider and version information

EF Core version: 7.0.5 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 7.0 Operating system: Windows IDE: Visual Studio 2022 17.8.7

roji commented 6 months ago

Can you please post a minimal, runnable sample? The above contains SQL, but we need the LINQ query and the model.

DanielStout5 commented 5 months ago

Here's a demo: https://github.com/DanielStout5/EfCoreOpenJson/tree/DistinctOrderByWarning

Turns out this warning is actually not inaccurate - the base query in use here actually did already a default OrderBy applied to it before the Distinct.

Is there a way to suppress this warning? We can't modify the base query in this case (which includes the OrderBy) and it doesn't affect the output query (the original OrderBy isn't even included in the SQL) and ideally we wouldn't have the Warning in the logs

roji commented 5 months ago

Suppressing warnings in covered in this page of the docs. I'll go ahead and close this as there doesn't seem to be a problem in EF, but if you need further assistance or think something is problematic don't hesitate to post back here.