diff --git a/Dapper/SqlMapper.Async.cs b/Dapper/SqlMapper.Async.cs index eade08cb2..d6d212b4f 100644 --- a/Dapper/SqlMapper.Async.cs +++ b/Dapper/SqlMapper.Async.cs @@ -1301,6 +1301,7 @@ static async IAsyncEnumerable Impl(IDbConnection cnn, Type effectiveType, Com bool wasClosed = cnn.State == ConnectionState.Closed; using var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader); DbDataReader? reader = null; + bool readerDrained = false; try { if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false); @@ -1312,6 +1313,7 @@ static async IAsyncEnumerable Impl(IDbConnection cnn, Type effectiveType, Com { if (reader.FieldCount == 0) { + readerDrained = true; yield break; } tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false)); @@ -1327,13 +1329,14 @@ static async IAsyncEnumerable Impl(IDbConnection cnn, Type effectiveType, Com yield return GetValue(reader, effectiveType, val); } while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore subsequent result sets */ } + readerDrained = true; command.OnCompleted(); } finally { if (reader is not null) { - if (!reader.IsClosed) + if (!readerDrained && !reader.IsClosed) { try { cmd?.Cancel(); } catch { /* don't spoil any existing exception */ }