Skip to content

Fix MultiMapAsync disposing the reader before unbuffered results are enumerated - #2229

Merged
mgravell merged 2 commits into
DapperLib:mainfrom
jinseojang0903:fix/multimapasync-unbuffered-reader-dispose
Nov 20, 2026
Merged

mgravell merged 2 commits into
DapperLib:mainfrom
jinseojang0903:fix/multimapasync-unbuffered-reader-dispose

Conversation

@jinseojang0903

Copy link
Copy Markdown
Contributor

Fixes #2099.

Problem

When calling any multi-map QueryAsync overload (e.g. QueryAsync<TFirst, TSecond, TReturn> or the Type[]-based QueryAsync<TReturn>)
with buffered: false, enumerating the returned sequence throws once the reader has already been disposed:

System.InvalidOperationException: Invalid attempt to call FieldCount when reader is closed.
at Dapper.SqlMapper.GetColumnHash(...)
at Dapper.SqlMapper.MultiMapImpl[...]+MoveNext()

Root cause

Both MultiMapAsync<TFirst,...,TSeventh,TReturn> and MultiMapAsync<TReturn> (Type[] overload) in SqlMapper.Async.cs wrapped the
DbDataReader in a using block. MultiMapImpl builds its result as a lazy, yield return-based IEnumerable<TReturn> that doesn't
start executing until the caller enumerates it. For buffered: false, the async method returns that un-enumerated sequence directly — so
the using disposes the reader immediately on return, before the caller ever gets a chance to read from it.

The single-type QueryAsync<T> path already avoids this by deferring disposal: it hands the reader into a small iterator
(ExecuteReaderSync) that only disposes it once the caller finishes enumerating. This PR applies the same pattern to both multi-map
overloads, adding a matching IEnumerable<TReturn>-based overload of ExecuteReaderSync for them to share.

Fix

  • SqlMapper.Async.cs: transfer reader ownership into the deferred sequence instead of disposing it unconditionally when buffered: false.
  • No change to the buffered: true path (already worked correctly, since .ToList() fully consumes the reader before the method returns).

Tests

Added two regression tests in AsyncTests.cs, following the existing TestMultiMapWithSplitAsync / TestMultiMapArbitraryWithSplitAsync
style:

  • TestMultiMapWithSplitUnbufferedAsync
  • TestMultiMapArbitraryWithSplitUnbufferedAsync

Both fail with the reported exception before this fix and pass after it. Full suite run locally (net8.0 + net10.0, SQL
Server/MySQL/Postgres) with no regressions.

…enumerated

Both the fixed-arity and Type[]-based MultiMapAsync overloads wrapped the
DbDataReader in a `using` that disposed it as soon as the async method
returned. For buffered:false calls the returned IEnumerable<TReturn> is a
lazy (yield-based) sequence that hasn't started executing yet, so the reader
was already closed by the time the caller enumerated it, throwing
ObjectDisposedException / "reader is closed" on first access.

Mirrors the disposal-deferral pattern already used by the single-type
QueryAsync<T> unbuffered path: transfer reader ownership into the returned
sequence instead of disposing it unconditionally.

Fixes DapperLib#2099

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PPzJgxak5nZ4u3j88ui5xX

@fathiaomar fathiaomar left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a question on line 950 regarding reader disposal and potential connection leaks during partial iteration

Comment thread Dapper/SqlMapper.Async.cs
}
wasClosed = false; // handing back open reader; rely on command-behavior
var deferred = ExecuteReaderSync(reader, results);
reader = null; // to prevent it being disposed before the caller gets to see it

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting reader = null prevents immediate disposal so unbuffered results can be streamed, but if the caller abandons or partially enumerates the returned IEnumerable, the reader and underlying connection won't be closed. How are connection leaks handled if iteration stops early?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the question! Early termination is covered: ExecuteReaderSync wraps the reader in a using inside an iterator, so the redder is disposed whenever the enumerator is disposed. That includes break or an exception inside a foreach, and LINQ operators like First(), Take() and Any(). If Dapper opened the connection itself, the reader is created with CommandBehavior.CloseConnection, so disposing the reader also closes the connection.

The only uncovered case is a caller who never enumerates the result, or who calls GetEnumerator() manually and never disposes it. That's the existing contract for buffered: false, and the single-type QueryAsync unbuffered path behaves the same way. This change follows that path exactly. Before this fix, the multi-map unbuffered path threw as soon as you enumerated it, so no new leak is introduced.

The previous GitHub Actions run expired while awaiting workflow approval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mgravell
mgravell merged commit cac0aed into DapperLib:main Nov 20, 2026
@mgravell

Copy link
Copy Markdown
Member

Verified and merged (via a merge commit — #2242 rewrote the same two methods minutes earlier, so I hand-merged the two: your reader-ownership transfer structure, carrying its resolved-CacheInfo pass-through). Faithfully mirroring the QueryAsync unbuffered hand-off was the right call, and the tests for both overloads made the combination easy to validate. This resolves #2099. Thanks!

This was referenced Nov 20, 2026
mvmorten added a commit to mvmorten/dashboard-starter that referenced this pull request Nov 23, 2026
Updated [Dapper](https://github.com/DapperLib/Dapper) from 2.1.89 to
2.1.100.

<details>
<summary>Release notes</summary>

_Sourced from [Dapper's
releases](https://github.com/DapperLib/Dapper/releases)._

## 2.1.100

## What's Changed
* Fix 2.1.86 unbox-gate regressions: array columns to interface members,
sql_variant to primitives by @​mgravell in
DapperLib/Dapper#2271
* Fix command disposal, parameter callbacks, handler-cache staleness,
static properties, and type-map races by @​mgravell in
DapperLib/Dapper#2272
* Fix deserializer cache race by @​jnm2 in
DapperLib/Dapper#2219
* Fix cache corruption due to CollectCacheGarbage call during
GridReader/Async queries by @​aklein53 in
DapperLib/Dapper#2218
* Fix false cache hit accounting on initial MultiMapAsync execution by
@​Nacl-HCl in DapperLib/Dapper#2242
* Fixes QueryMultiple corrupting a later Query<T>'s DynamicParameters --
fixes #​243, #​2091 by @​NadeemAfana in
DapperLib/Dapper#2214
* Don't cancel the command after QueryUnbufferedAsync completes normally
by @​aaronwilliams-tesouro in
DapperLib/Dapper#2245
* Preserve Size set by type handlers for string parameters by
@​JiuYue0820 in DapperLib/Dapper#2221
* Fix MultiMapAsync disposing the reader before unbuffered results are
enumerated by @​jinseojang0903 in
DapperLib/Dapper#2229
* Stop boxing values read via GetFieldValue<T> for the error message by
@​Giorgi in DapperLib/Dapper#2265
* Fix list initializer in bulk Execute README example by @​dajiaohuang
in DapperLib/Dapper#2243

## New Contributors
* @​aklein53 made their first contribution in
DapperLib/Dapper#2218
* @​Nacl-HCl made their first contribution in
DapperLib/Dapper#2242
* @​NadeemAfana made their first contribution in
DapperLib/Dapper#2214
* @​aaronwilliams-tesouro made their first contribution in
DapperLib/Dapper#2245
* @​JiuYue0820 made their first contribution in
DapperLib/Dapper#2221
* @​jinseojang0903 made their first contribution in
DapperLib/Dapper#2229
* @​dajiaohuang made their first contribution in
DapperLib/Dapper#2243

**Full Changelog**:
DapperLib/Dapper@2.1.89...2.1.100

Commits viewable in [compare
view](DapperLib/Dapper@2.1.89...2.1.100).
</details>

[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=Dapper&package-manager=nuget&previous-version=2.1.89&new-version=2.1.100)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Michael Mortensen <mvmorten@users.noreply.github.com>
This was referenced Nov 23, 2026
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.

MultiMapAsync disposes reader in unbuffered query

3 participants