Skip to content

LINQ: First/FirstOrDefault/Single after SelectMany (Fixes #5921) - #5922

Merged
jeremydmiller merged 2 commits into
masterfrom
fix/5921-selectmany-first
Nov 15, 2026
Merged

jeremydmiller merged 2 commits into
masterfrom
fix/5921-selectmany-first

Conversation

@jeremydmiller

@jeremydmiller jeremydmiller commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Fixes #5921

Root cause

FirstAsync() / FirstOrDefaultAsync() / SingleAsync() / SingleOrDefaultAsync() pass their mode through the provider, and LinqQueryParser.BuildStatements() puts it on the last collection usage. For Query<T>().SelectMany(x => x.Children).FirstAsync() there is only one usage, the one that holds the SelectMany(), so:

  1. ProcessSingleValueModeIfAny applied the mode to the parent statement: SingleValue = true and LIMIT 1 on the documents being flattened.
  2. compileNext then built a fresh CollectionUsage for the flattened rows without the mode, so the final (flattened) statement stayed a list. No handler fit the scalar TResult: NotSupportedException: Marten does not know how to use result type ....

The predicate overloads (FirstAsync(x => ...)) and SelectMany(...).Where(...)/OrderBy(...).First*() already worked, because the extra operator creates a downstream usage that carries the mode. Only the bare shape was broken. Even if it hadn't thrown, the parent LIMIT 1 would have returned nothing whenever the first parent had an empty collection.

The fix

src/Marten/Linq/CollectionUsage.Compilation.cs, which touches no parser and no Take/Skip/Count code:

  • New SingleValueModeAppliesToFlattenedRows. It is true only for First/FirstOrDefault/Single/SingleOrDefault on a usage that ends in a plain SelectMany() with nothing downstream. GroupJoin flattening (GroupJoinData / SelectManyCallExpression) is excluded because it already carries the mode onto its join statement.
  • ProcessSingleValueModeIfAny leaves such a usage's parent statement alone.
  • compileNext hands the mode to the usage that builds the flattened statement. That statement gets SingleValue, LIMIT 1 (First) / LIMIT 2 (Single) and an OneResultHandler, the same way the already-working SelectMany(...).Where(...).First() path does.

Count/LongCount/Any keep their existing jsonb_array_length / NotEmpty SelectMany shortcuts.

Tests

New LinqTests/Acceptance/first_and_single_after_select_many.cs (36 tests, clears its own document types). Every case is compared with LINQ to Objects over the same seeded data:

  • First / FirstOrDefault / Single / SingleOrDefault, with and without predicate, after SelectMany over child documents and over a value collection (int[]), plus SelectMany followed by Where / OrderBy / OrderByDescending.
  • Empty sequences: FirstOrDefault returns null / 0, First and Single throw InvalidOperationException. Single / SingleOrDefault with 2+ rows throw InvalidOperationException. This is the same type Marten's OneResultHandler throws elsewhere, and the tests assert it matches LINQ to Objects.
  • The parents with nothing to flatten are seeded first, so a parent-side LIMIT would show up as a wrong result.
  • LIMIT placement: the executed command has exactly one LIMIT, at the end on the flattened rows (1 for First, 2 for Single), and none inside the CTE that reads the parents.
  • The two shapes from the issue on Target (Children, which is the same type as the parent, and NumberArray).

preview_command_matches_the_executed_command (#5918, already on master): removed the fetchOne: false skips for select_many_over_a_child_document_collection and select_many_over_a_child_value_collection, plus the comment explaining them. The fetchOne parameter had no callers left, so it is gone too. ToCommand(FetchType.FetchOne) and the executed First/FirstOrDefault now agree for both SelectMany shapes.

Red on master (1d13d0f3a, net10.0, same tests against the unfixed product file)

  • first_and_single_after_select_many: 13 failed / 23 passed. 11 behavioural failures, every one a NotSupportedException: Marten does not know how to use result type ... (directly, or as the wrong exception where InvalidOperationException was expected). The other 2 are the First LIMIT-placement tests.
  • preview_command_matches_the_executed_command with the skips removed: 2 failed / 16 passed, the two SelectMany shapes.

Green with the fix

Suite TFM Result
LinqTests (full) net10.0 1753 / 1753
LinqTests (full) net11.0 1777 / 1777
DocumentDbTests (full) net10.0 1270 passed, 1 skipped, 0 failed
CompiledQueryTests (full) net10.0 9 / 9

9.x

9.0 has the same bug. On origin/9.0 (d824a8dcc), the same 36 tests show 13 red without the fix, the same set as master (10 with does not know how to use result type), and 36/36 green with it. Backport: #5923 against 9.0. CI was dispatched by hand there, because tests.yml does not trigger for that branch.

🤖 Generated with Claude Code

jeremydmiller and others added 2 commits November 15, 2026 09:40
…5921)

A First/Single mode passed by the provider (FirstAsync() and friends) lands on the
last collection usage. When that usage ends in a plain SelectMany() with nothing
downstream, the mode was applied to the PARENT statement (LIMIT on the documents
being flattened) and the flattened statement stayed a list, so no handler fit the
result type: "Marten does not know how to use result type ...".

The mode now travels to the usage that builds the flattened statement, so it gets
SingleValue and LIMIT 1 (First) / LIMIT 2 (Single) and an OneResultHandler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n tests

FirstAsync()/FirstOrDefaultAsync() after SelectMany() execute now (#5921), so the two
SelectMany shapes no longer skip FetchOne, and the fetchOne knob has no callers left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeremydmiller
jeremydmiller merged commit ff3aca2 into master Nov 15, 2026
32 checks passed
@jeremydmiller
jeremydmiller deleted the fix/5921-selectmany-first branch November 15, 2026 16:28
jeremydmiller added a commit that referenced this pull request Nov 15, 2026
[9.0] LINQ: First/FirstOrDefault/Single after SelectMany (backport of #5922)
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.

LINQ: First/FirstOrDefault/Single after SelectMany throws NotSupportedException at execution

1 participant