I'm using Dapper and trying to retrieve a short from the database and would like to do this without grabbing it from a collection.
I've got the following code, which doesn't work because QueryAsync<short>
returns IEnumerable<short>
.
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);
}
Can I get Dapper to return a single value, instead of a collection?
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);