Selecting Scalar Values With Dapper

Dapper provides two methods for selecting scalar (simple single) values along with their asynchronous counterparts.

Method Description
ExecuteScalar Returns a dynamic type
ExecuteScalar<T> Returns an instance of the type specified by the T type parameter
ExecuteScalarAsync Returns a dynamic type asynchronously
ExecuteScalarAsync<T> Returns an instance of the type specified by the T type parameter asynchronously

The ExecuteScalar methods

using (var connection = new SQLiteConnection(connString))
{
    var sql = "select count(*) from products";
    var count = connection.ExecuteScalar(sql);
    Console.WriteLine($"Total products: {count}");
}

If you want to perform any operations on the returned value, you will need to cast or convert it to its expected type. Alternatively, use the version of ExecuteScalar that takes a generic parameter and specify the return type explicitly:

using (var connection = new SQLiteConnection(connString))
{
    var sql = "select count(*) from products";
    var count = connection.ExecuteScalar<int>(sql);
    Console.WriteLine($"Total products: {count}");
}

Asynchronous Operations

using (var connection = new SQLiteConnection(connString))
{
    var sql = "select count(*) from products";
    var count = await connection.ExecuteScalarAsync(sql);
    Console.WriteLine($"Total products: {count}");
}
using (var connection = new SQLiteConnection(connString))
{
    var sql = "select count(*) from products";
    var count = await connection.ExecuteScalarAsync<int>(sql);
    Console.WriteLine($"Total products: {count}");
}
Last updated: 21/05/2019 13:53:55