Skip to content

Query: Simplify aliases for complex projection if being used in order by clause #6703

@smitpatel

Description

@smitpatel

For query like this

selection = db.Nodes.Include(x => x.NodeRecords)
        .Select(s => new HighNode()
        {
            Name = s.Name,
            Change = s.NodeRecords.OrderByDescending(o => o.NodeRecordId).Skip(days).FirstOrDefault().Change
        }).OrderByDescending(t => t.Change).Take(100).ToList();

We generate Sql like this

SELECT TOP(@__p_1) [x].[Name], (
    SELECT [o0].[Change]
    FROM [NodeRecords] AS [o0]
    WHERE [x].[Name] = [o0].[Node_Name]
    ORDER BY [o0].[NodeRecordId] DESC
    OFFSET @__days_0 ROWS FETCH NEXT 1 ROWS ONLY
)
FROM [Nodes] AS [x]
ORDER BY (
    SELECT [o].[Change]
    FROM [NodeRecords] AS [o]
    WHERE [x].[Name] = [o].[Node_Name]
    ORDER BY [o].[NodeRecordId] DESC
    OFFSET @__days_0 ROWS FETCH NEXT 1 ROWS ONLY
) DESC

We can just alias the subquery in projection and use alias in order by clause as enhancement.

For model and more info see #6257

Metadata

Metadata

Assignees

Labels

No labels
No labels
No fields configured for Feature.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions