Skip to content

2.3. Multiple(command, params) connection extension

Vedran Bilopavlović edited this page Mar 26, 2021 · 5 revisions

Reading the data from multiple result-sets with the Multiple(command, params) extension

Takes command with optional parameters and returns disposable reader instance that can read and map from multiple commands (separated in SQL by ;).

Reader instance has the following methods exposed:

  • Read<T1, T2, T3 ...>() - Reads and maps the current result set. Takes generic parameters and maps using the same logic as the Read extensions.

  • Next() - Advances to the next result set for reading and returns True; if the current result set is the last result set, returns False

Simple example:

var sql = @"
    SELECT TOP 1 CustomerID, CustomerName, ContactName FROM Customers;
    SELECT TOP 1 CategoryID, CategoryName, Description FROM Categories";

using var reader = connection.Multiple(sql);
var customer = reader.Read<Customer>().Single();
reader.Next();
var category = reader.Read<Category>().Single();
		
Console.WriteLine($"customer = {customer.CustomerName.Trim()}, category = {category.CategoryName}"); //customer = Alfreds Futterkiste, category = Beverages

Try it yourself

Iterate result-sets example:

var sql = @"
    SELECT TOP 1 CustomerID, CustomerName, ContactName FROM Customers where CustomerID = 1;
    SELECT TOP 1 CustomerID, CustomerName, ContactName FROM Customers where CustomerID = 2;
    SELECT TOP 1 CustomerID, CustomerName, ContactName FROM Customers where CustomerID = 3;
    SELECT TOP 1 CustomerID, CustomerName, ContactName FROM Customers where CustomerID = 4;
    SELECT TOP 1 CustomerID, CustomerName, ContactName FROM Customers where CustomerID = 5;";
using var reader = connection.Multiple(sql);
do
{
    var customer = reader.Read<Customer>().Single();
    Console.WriteLine(customer.CustomerID);   
}
while(reader.Next());

Try it yourself

For more information and options when working with parameters see also

See also