Skip to content

Commit

Permalink
Query: Remove constants from grouping key when adding to SQL GROUP BY (
Browse files Browse the repository at this point in the history
…#17114)

Resolves #14152
  • Loading branch information
kosinsky authored and smitpatel committed Aug 15, 2019
1 parent bda51d2 commit f13ae3b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,10 @@ private void AppendGroupBy(Expression keySelector)
switch (keySelector)
{
case SqlExpression sqlExpression:
_groupBy.Add(sqlExpression);
if (!(sqlExpression is SqlConstantExpression))
{
_groupBy.Add(sqlExpression);
}
break;

case NewExpression newExpression:
Expand Down Expand Up @@ -1148,7 +1151,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor)

var groupBy = _groupBy.ToList();
_groupBy.Clear();
_groupBy.AddRange(GroupBy.Select(e => (SqlExpression)visitor.Visit(e)));
_groupBy.AddRange(GroupBy.Select(e => (SqlExpression)visitor.Visit(e)).Where(e => !(e is SqlConstantExpression)));

Having = (SqlExpression)visitor.Visit(Having);

Expand Down
17 changes: 17 additions & 0 deletions test/EFCore.Specification.Tests/Query/GroupByQueryTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.TestModels.Northwind;
Expand Down Expand Up @@ -262,6 +263,22 @@ public virtual Task GroupBy_Property_Select_key_multiple_times_and_aggregate(boo
e => e.Key1);
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task GroupBy_Property_Select_Key_with_constant(bool isAsync)
{
return AssertQuery<Order>(
isAsync,
os => os.GroupBy(o => new { Name = "CustomerID", Value = o.CustomerID }).Select(
g =>
new
{
g.Key,
Count = g.Count()
}),
e => e.Key.Value);
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task GroupBy_aggregate_projecting_conditional_expression_based_on_group_key(bool isAsync)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,16 @@ FROM [Orders] AS [o]
GROUP BY [o].[CustomerID]");
}

public override async Task GroupBy_Property_Select_Key_with_constant(bool isAsync)
{
await base.GroupBy_Property_Select_Key_with_constant(isAsync);

AssertSql(
@"SELECT N'CustomerID' AS [Name], [o].[CustomerID] AS [Value], COUNT(*) AS [Count]
FROM [Orders] AS [o]
GROUP BY [o].[CustomerID]");
}

public override async Task GroupBy_aggregate_projecting_conditional_expression_based_on_group_key(bool isAsync)
{
await base.GroupBy_aggregate_projecting_conditional_expression_based_on_group_key(isAsync);
Expand Down

0 comments on commit f13ae3b

Please sign in to comment.