Elena
Elena

Reputation: 1

How to read i-result set and skip others in QueryMultiple

is it possible to skip result sets in QueryMultiple and get just i-result set?

Let's say we have 3 (or more!) result sets

string sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID; SELECT * FROM InvoiceItem WHERE InvoiceID = @InvoiceID; SELECT * FROM InvoiceConfiguration WHERE InvoiceID = @InvoiceID;";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    using (var multi = connection.QueryMultiple(sql, new {InvoiceID = 1}))
    {
        var invoice = multi.Read<Invoice>().First();
    
        //I don't need the second result set, only 1 and 3
        var unused = multi.Read<InvoiceItem>().ToList();

        var invoiceConfiguration = multi.Read<InvoiceConfiguration>().ToList();
    }
}

Thank you in advance!

Upvotes: 0

Views: 790

Answers (1)

Charlieface
Charlieface

Reputation: 71203

There is a method on GridReader (the result of QueryMultiple) called NextResult which in turn moves the IDataReader forward to the next resultset, but unfortunately it's private. It might be worth putting in a feature request for it.

You could instead just dispose the enumerator immediately

multi.Read<InvoiceItem>(buffered: false).Dispose();

This does have the downside of reading at least one row though, but that's unlikely to make much difference.

Or for async you can do this

(await multi.ReadAsync<InvoiceItem>(buffered: false)).Dispose();

You can even create extension functions for these

public void NextResult(this SqlMapper.GridReader reader) =>
    multi.Read<dynamic>(buffered: false).Dispose();

public async Task NextResultAsync(this SqlMapper.GridReader reader) =>
    (await multi.ReadAsync<dynamic>(buffered: false)).Dispose();

Upvotes: 1

Related Questions