Repository navigation
LINQ: First/FirstOrDefault/Single after SelectMany (Fixes #5921) - #5922
Merged
Merged
Conversation
…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
added a commit
that referenced
this pull request
Nov 15, 2026
[9.0] LINQ: First/FirstOrDefault/Single after SelectMany (backport of #5922)
This was referenced Nov 15, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #5921
Root cause
FirstAsync()/FirstOrDefaultAsync()/SingleAsync()/SingleOrDefaultAsync()pass their mode through the provider, andLinqQueryParser.BuildStatements()puts it on the last collection usage. ForQuery<T>().SelectMany(x => x.Children).FirstAsync()there is only one usage, the one that holds theSelectMany(), so:ProcessSingleValueModeIfAnyapplied the mode to the parent statement:SingleValue = trueandLIMIT 1on the documents being flattened.compileNextthen built a freshCollectionUsagefor the flattened rows without the mode, so the final (flattened) statement stayed a list. No handler fit the scalarTResult:NotSupportedException: Marten does not know how to use result type ....The predicate overloads (
FirstAsync(x => ...)) andSelectMany(...).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 parentLIMIT 1would 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:SingleValueModeAppliesToFlattenedRows. It is true only for First/FirstOrDefault/Single/SingleOrDefault on a usage that ends in a plainSelectMany()with nothing downstream. GroupJoin flattening (GroupJoinData/SelectManyCallExpression) is excluded because it already carries the mode onto its join statement.ProcessSingleValueModeIfAnyleaves such a usage's parent statement alone.compileNexthands the mode to the usage that builds the flattened statement. That statement getsSingleValue,LIMIT 1(First) /LIMIT 2(Single) and anOneResultHandler, the same way the already-workingSelectMany(...).Where(...).First()path does.Count/LongCount/Any keep their existing
jsonb_array_length/NotEmptySelectMany 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:int[]), plus SelectMany followed by Where / OrderBy / OrderByDescending.FirstOrDefaultreturns null /0,FirstandSinglethrowInvalidOperationException.Single/SingleOrDefaultwith 2+ rows throwInvalidOperationException. This is the same type Marten'sOneResultHandlerthrows elsewhere, and the tests assert it matches LINQ to Objects.LIMIT, at the end on the flattened rows (1 for First, 2 for Single), and none inside the CTE that reads the parents.Target(Children, which is the same type as the parent, andNumberArray).preview_command_matches_the_executed_command(#5918, already on master): removed thefetchOne: falseskips forselect_many_over_a_child_document_collectionandselect_many_over_a_child_value_collection, plus the comment explaining them. ThefetchOneparameter 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 aNotSupportedException: Marten does not know how to use result type ...(directly, or as the wrong exception whereInvalidOperationExceptionwas expected). The other 2 are the First LIMIT-placement tests.preview_command_matches_the_executed_commandwith the skips removed: 2 failed / 16 passed, the two SelectMany shapes.Green with the fix
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 withdoes not know how to use result type), and 36/36 green with it. Backport: #5923 against9.0. CI was dispatched by hand there, becausetests.ymldoes not trigger for that branch.🤖 Generated with Claude Code