question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Help Aggregating Data on an IGrouping

See original GitHub issue

Ask a question

I am having trouble selecting aggregate data after a group by.

For reference, here is SQL that emulates what I am trying to do:

select   
ut.teamid as TeamId, sum(p.value) as Value
from userteams ut
join users u on u.id=ut.UserId
join points p on p.UserId = u.id
group by ut.teamid

Here is my code currently:

var rankedTeamForMonth = query // Query is a query on userteams (same model as from the SQL above)
   .GroupBy(x => x.TeamId)
   .Select(x =>
          new 
           {
                    Value = x.Sum(ut => ut.User.Points.Sum(y => y.Value)),
                    TeamId = x.Key,
           }
   );

I get an error that Query could not be translated

Stack Trace:

   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|15_0(ShapedQueryExpression translated, <>c__DisplayClass15_0& )
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
   at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
   at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()

EF Core version: 5.0.8 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 5.0 Operating system: Windows 10 IDE: Rider

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
rojicommented, Sep 26, 2021

@jacobhjustice with EF Core 6.0, you can achieve what you want with the following query:

var rankedTeamForMonth = ctx.UserTeams
    .GroupBy(x => x.TeamId)
    .Select(x =>
        new
        {
            Value = x.SelectMany(ut => ut.User.Points).Sum(p => p.Value),
            Id = x.Key,
        });

In other words, instead of a nested Sum within a sum, simply flatten everything first and then perform a single Sum. I’d advise using EF Core 6.0.0 rc1 (which is production-ready version with a go-live license).

2reactions
rojicommented, Sep 23, 2021

@jacobhjustice can you please submit a runnable code sample producing the translation exception? It’s difficult to know exactly what you’re doing from a the query fragment above.

Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - GroupBy then do aggregation on results for each group
Now, I want to produce an IEnumerable<T> with an IGrouping or anonymous type that has two properties 1) the name (the key) and...
Read more >
IGrouping<TKey,TElement> Interface (System.Linq)
For example, you can access the values by using a foreach in Visual C# or For Each in Visual Basic loop to iterate...
Read more >
Grouping and Aggregating Data - LINQ Guide
By grouping our objects, we can perform aggregate functions like count, sum, max and min on our sets, and create meaningful information from ......
Read more >
84 - LINQ - Group - Aggregate Data
The group clause is used to group data; it returns a sequence of IGrouping<TKey, TElement> objects. Items that match the group key value,...
Read more >
Grouping Linq Aggregates in C# - Simple Thread
Using aggregates such as “Count”, “Average”, “Sum” etc… is pretty easy in simple queries. Lets say we have a table like this: Product...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found