In EF Core 10, which GroupBy queries translate to a SQL GROUP BY, and what happens when a query returns the groups themselves?
answer
- IGrouping has no SQL shape
- key plus aggregates becomes GROUP BY
- aggregate in Where becomes HAVING
- final GroupBy: ORDER BY, grouped on client
- AsEnumerable before GroupBy as fallback
basics
~20 sGroupBy followed by a Select of the key and aggregates such as Count or Sum becomes GROUP BY, and an aggregate filter becomes HAVING. A query ending in GroupBy is sent as an ordered SELECT and grouped on the client.
solid answer
~40 sSQL `GROUP BY` can only return grouping keys and aggregates, while LINQ's `GroupBy` returns `IGrouping<TKey, TElement>`, which no table can hold. So EF Core translates the shape that matches SQL: `GroupBy(w => w.Status).Select(g => new { g.Key, Count = g.Count() })` becomes `GROUP BY` with `COUNT(*)`, and `Where(g => g.Count() > 5)` after the grouping becomes `HAVING`. A query whose **final** operator is `GroupBy` also works: EF sends a plain `SELECT ... ORDER BY key` and builds the groups after the rows arrive, so it transfers every row. Shapes that fit neither — for example composing further on the raw grouping — throw an `InvalidOperationException` saying the pattern cannot be translated. The remedy is to aggregate on the server, or to call `AsEnumerable()` before `GroupBy` once the rows are already few.
go deeper
Remember that GroupBy followed by a Select of the key and Count or Sum turns into SQL GROUP BY.
Explain why IGrouping has no SQL form, which shapes become GROUP BY or HAVING, and what a final GroupBy actually sends.
Spot report queries that group whole rows on the client, rewrite them as aggregates, and verify per-group shapes with the generated SQL.
Decide when reporting aggregates belong in EF queries, in database views, or in a separate read model, given data volume and change rates.
## The mismatch LINQ's `GroupBy` produces `IGrouping<TKey, TElement>`: a key plus an enumerable of the original elements. SQL's `GROUP BY` produces one row per group containing only **grouping keys and aggregates**. There is no column type for "a list of rows", so EF Core can translate a LINQ grouping only when the query reduces each group to scalars, or when it can rebuild the groups on the client. ## Shapes that translate to GROUP BY On the project dashboard, counting work items per status: ```csharp var byStatus = await db.WorkItems .Where(w => w.ProjectId == projectId) .GroupBy(w => w.Status) .Select(g => new { Status = g.Key, Count = g.Count(), Points = g.Sum(w => w.Points) }) .ToListAsync(); ``` ```sql SELECT w."Status", count(*)::int AS "Count", COALESCE(sum(w."Points"), 0)::int AS "Points" FROM "WorkItems" AS w WHERE w."ProjectId" = @projectId GROUP BY w."Status" ``` Rules of thumb: - **Key and aggregates in the projection** translate. The standard aggregates are `Count`, `LongCount`, `Sum`, `Min`, `Max` and `Average`; providers may map more. - **An aggregate in a `Where` or `OrderBy` after `GroupBy`** translates to `HAVING` or an ordering on the aggregate. - **Everything before `GroupBy`** may be any translatable query, and once aggregates have removed the groupings you can keep composing (`OrderByDescending`, `Take`). - **Grouping by a constant**, `GroupBy(_ => 1)`, puts all rows in one group so you can compute several aggregates in a single statement. Filtering groups by an aggregate is the other common report shape. Projects whose open items exceed a threshold: ```csharp var crowded = await db.WorkItems .Where(w => !w.IsDone) .GroupBy(w => w.ProjectId) .Where(g => g.Count() > 50) .Select(g => new { ProjectId = g.Key, Open = g.Count() }) .ToListAsync(); ``` The `Where` after `GroupBy` becomes a `HAVING` clause on the count, so only the qualifying projects leave the database. ## Returning the groups themselves `await db.WorkItems.GroupBy(w => w.Status).ToListAsync()` asks for `IGrouping` objects. Current EF Core supports this when `GroupBy` is the **final operator**: EF sends `SELECT <all columns> FROM "WorkItems" ORDER BY "Status"` and creates the groups after the rows are returned, much as it assembles collections for `Include`. It is correct but it transfers **every row**, so it is not a substitute for an aggregate. ## Shapes that fail When the grouping is composed in a way that fits neither pattern, EF Core throws an `InvalidOperationException`. Depending on the shape, the message is the general *"could not be translated"* error or the relational *"Unable to translate the given 'GroupBy' pattern. Call 'AsEnumerable' before 'GroupBy' to evaluate it client-side."* Typical causes: - a grouping key that is a client-side method call; - further LINQ over the raw `IGrouping` that is not an aggregate; - projecting the group without reducing it where EF cannot rebuild it. Some per-group shapes, such as taking the newest item of each group after ordering inside the group, can translate with a window function on relational providers; check with `ToQueryString()` rather than assuming. ## Choosing a fix | Need | Approach | |---|---| | Counts or totals per key | `GroupBy` + aggregate projection (server) | | Filter groups by a total | aggregate in `Where` after `GroupBy` (`HAVING`) | | All rows, grouped for display | final `GroupBy` (ordered `SELECT`, client grouping) or project then group in memory | | A grouping EF cannot translate, on a small result | filter on the server, then `AsEnumerable()` and group in .NET | 1. Prefer the aggregate shape; it keeps the work and the data on the server. 2. If you must group whole rows, filter as narrowly as possible first. 3. Verify the generated SQL; `GroupBy` is where assumptions break most often.
- How do you count work items and sum story points over the whole project in one SQL statement with EF Core?Group by a constant: `GroupBy(_ => 1).Select(g => new { Count = g.Count(), Points = g.Sum(w => w.Points) })` after the `Where`. All rows fall into one group, so EF emits a single `SELECT` with both aggregates. Separate `CountAsync` and `SumAsync` calls would each be their own round trip.
- Why is a final GroupBy not a performance fix for a report that only needs counts?A final `GroupBy` makes EF fetch every row ordered by the key and build the groups in .NET; the count would then be computed on the client. Projecting `g.Key` and `g.Count()` sends a real `GROUP BY` and returns one row per key.
- EF Core never translates GroupBy; it always runs in memory.
- A final GroupBy returns one row per key from the database.
- Any C# expression is allowed as the grouping key.
- HAVING requires raw SQL in EF Core.