diff --git a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.Helper.cs b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.Helper.cs index b1681821729..25edf3bd1f9 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.Helper.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.Helper.cs @@ -154,6 +154,29 @@ public ProjectionIndexRemappingExpressionVisitor( } } + private sealed class UseAliasExpressionVisitor : ExpressionVisitor + { + private readonly SelectExpression _queryExpression; + + public UseAliasExpressionVisitor(SelectExpression queryExpression) + { + _queryExpression = queryExpression; + } + + [return: NotNullIfNotNull("expression")] + public override Expression? Visit(Expression? expression) + { + foreach (var x in _queryExpression.Projection) + { + if (x.Expression.Equals(expression)) + { + return new SqlFragmentExpression(x.Alias); + } + } + return base.Visit(expression); + } + } + private sealed class SqlRemappingVisitor : ExpressionVisitor { private readonly SelectExpression _subquery; diff --git a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs index e6c7ddf1997..65e0931c8c7 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs @@ -1570,6 +1570,12 @@ Expression CopyProjectionToOuter(SelectExpression innerSelectExpression, Express _projectionMapping.Clear(); _projectionMapping = result; + var useAliasVisitor = new UseAliasExpressionVisitor(this); + for (var i = 0; i < _orderings.Count; i++) + { + _orderings[i] = useAliasVisitor.VisitAndConvert(_orderings[i], nameof(ApplyProjection)); + } + return shaperExpression; }