Dapper Multi‑Statement Operations with QueryMultiple
QueryMultiple(): Executes multiple SQL queries over one open connection and returns multiple result sets at once.- Separate multiple SQL statements with a semicolon
;. - The return type is
GridReader. Call.Read<T>()to read each dataset sequentially in order. - Benefit: Only one database connection is created, cutting network overhead from repeated queries.
Example
using System;
using System.Collections.Generic;
using System.Data;
using MySql.Data.MySqlClient;
using Dapper;
using System.Configuration;
namespace ConsoleApp4
{
public class Customers
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
public class Book
{
public string Title { get; set; }
}
class Program
{
static void Main(string[] args)
{
var connStr = ConfigurationManager.ConnectionStrings["CustomerConnection"].ConnectionString;
using (IDbConnection db = new MySqlConnection(connStr))
{
// Multiple SQL separated by semicolons
string sql = "SELECT * FROM Customers; SELECT * FROM Book;";
// Get multi‑result reader
var multiReader = db.QueryMultiple(sql);
// Read in the exact order of SQL statements
IEnumerable<Customers> customerList = multiReader.Read<Customers>();
IEnumerable<Book> bookList = multiReader.Read<Book>();
multiReader.Dispose(); // Dispose reader resources
}
Console.ReadKey();
}
}
}Code language: C# (cs)
- Read order must strictly match SQL statement order
The first SELECT must be read first. Wrong ordering triggers exceptions. - Do not call Read more times than the number of available result sets.
- For MySQL, confirm multi‑statement support is enabled in your connection string (usually enabled by default).
QueryMultipleworks best for SELECT‑only queries; use caution mixing INSERT / UPDATE / DELETE. Transactions are recommended instead.
Parameter‑Based Multi‑Statement Query
string sql = "SELECT * FROM student WHERE Id=@id; SELECT * FROM book WHERE Id=@id;";
using var multiReader = db.QueryMultiple(sql, new { id = 1 });
var stu = multiReader.ReadFirstOrDefault<Student>();
var book = multiReader.ReadFirstOrDefault<Book>();Code language: C# (cs)
Multi‑statement Operations
Previous: IN Query