The method QueryUnbufferedAsync
has been added in the v2.0.138 to cover a very old mistake that requires breaking changes. The QueryAsync extends the IDbConnection
however the IDbConnection
class doesn't have the async
method as NickCraver commented here.
The Async
method should extend the DbConnection
and not the IDbConnection
, which will be done when the next major v3 version is released.
Dapper Query Unbuffered Async
The method QueryUnbufferedAsync
has 2 main purposes:
- Selecting multiple data from your database asynchronously
- Loading data retrieved on demand (similar to
buffered = false
)
In this example, we will start by using Dapper Plus to make the setup easier by using the CreateTable method and BulkInsert method. Then, showing how to use the QueryUnbufferedAsync
method from Dapper in a foreach
statement using the await
keyword and ConfigureAwait
method:
language-csharp
|
public static async Task Main()
{
var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer());
// CREATE table
connection.CreateTable<Customer>();
// SEED data
var customers = new List<Customer>();
customers.Add(new Customer() { Name = "Jonathan Magnan", Email = "info@zzzprojects.com" });
customers.Add(new Customer() { Name = "ZZZ Projects", Email = "sales@zzzprojects.com" });
customers.Add(new Customer() { Name = "Sara", Email = "sara@zzzprojects.com" });
connection.BulkInsert(customers);
// SELECT data
await foreach (var customer in connection.QueryUnbufferedAsync<Customer>("SELECT * FROM Customers WHERE CustomerID > @ID", new { ID = 1 }).ConfigureAwait(false))
{
Console.WriteLine($"CustomerID: {customer.CustomerID}; Name: {customer.Name}; Email: {customer.Email}");
}
}