How to retrieve a single value from the database using Dapper
Either you can use ExecuteScalarAsync
or Single()
with ExecuteScalarAsync
you can retrieve a single value from database using Dapper.
short status;
using (var sqlConnection = new SqlConnection(connectionString))
{
var parameters = new DynamicParameters();
parameters.Add("@ID", ID, DbType.Int32, ParameterDirection.Input);
await sqlConnection.OpenAsync();
status = await sqlConnection.ExecuteScalarAsync<short>("SELECT [StatusID] FROM [MyTable] WHERE [ID] = @ID", parameters, commandTimeout: _sqlCommandTimeoutInSeconds);
}
Single()
can be used in this way
short status;
using (var sqlConnection = new SqlConnection(connectionString))
{
var parameters = new DynamicParameters();
parameters.Add("@ID", ID, DbType.Int32, ParameterDirection.Input);
await sqlConnection.OpenAsync();
status = await sqlConnection.QueryAsync<short>("SELECT [StatusID] FROM [MyTable] WHERE [ID] = @ID", parameters, commandTimeout: _sqlCommandTimeoutInSeconds).Single();
}
FYI, Dapper has now added both QuerySingle
and QuerySingleAsync
as well as their corresponding OrDefault
variants... usage for QuerySingleOrDefaultAsync
is:
await connection.QuerySingleOrDefaultAsync<short>(sql);
You should use ExecuteScalar
:
status = await sqlConnection.ExecuteScalarAsync<short>("SELECT [StatusID] FROM [MyTable] WHERE [ID] = @ID", parameters, commandTimeout: _sqlCommandTimeoutInSeconds)