Skip to content

Support Count/LongCount after GroupBy().Select() (#4278)#4281

Merged
jeremydmiller merged 1 commit intomasterfrom
fix-4278-linq
Apr 22, 2026
Merged

Support Count/LongCount after GroupBy().Select() (#4278)#4281
jeremydmiller merged 1 commit intomasterfrom
fix-4278-linq

Conversation

@jeremydmiller
Copy link
Copy Markdown
Member

Summary

.GroupBy(...).Select(...).CountAsync() was throwing System.NotSupportedException: Marten does not know how to use result type int. Two adjustments in CollectionUsage.Compilation.cs:

  • Transfer SingleValueMode and IsAny from the grouping usage itself in CompileGroupBy, not just from groupingUsage.Inner. Terminal aggregates applied directly after the Select(...) projection land on the grouping usage, and were previously dropped.
  • In ProcessSingleValueModeIfAny, when Count/LongCount is being applied and the statement already has GROUP BY columns, wrap the query in a CTE and count its rows — mirroring the existing IsDistinct path. Replacing the SELECT with count(*) in-place would have counted rows within each group instead of counting the groups themselves.

Fixes #4278.

Test plan

  • New regression tests group_by_count and group_by_long_count in group_by_operator.cs — both fail on master with NotSupportedException, both pass with this fix.
  • Full LinqTests suite: 1255 passed, 0 failed, 1 skipped (pre-existing skip, unrelated).

🤖 Generated with Claude Code

.GroupBy(...).Select(...).CountAsync() was throwing
"Marten does not know how to use result type int" because the
SingleValueMode set by CountAsync() on the grouping usage was never
transferred to the outer CollectionUsage, and the Count path didn't
know how to count groups instead of underlying rows.

Two small fixes in CompileGroupBy / ProcessSingleValueModeIfAny:

- Transfer SingleValueMode and IsAny from the grouping usage itself
  (not just from groupingUsage.Inner), so terminal aggregates applied
  directly after the Select projection are seen.
- When Count/LongCount is applied and the statement already has
  GROUP BY columns, wrap the query in a CTE and count its rows — the
  same pattern the Distinct path already uses. Replacing the SELECT
  with count(*) would have counted rows within each group instead of
  counting the groups themselves.

Fixes #4278.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Count applied after GroupBy and Select

1 participant