我正在使用Dapper并尝试从数据库中检索一个短片,并希望在不从集合中抓取它的情况下执行此操作。
我已经获得了以下代码,但由于QueryAsync<short>
返回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);
}
我可以让Dapper返回单个值而不是集合吗?
答案 0 :(得分:11)
仅供参考,Dapper现在已经添加了QuerySingle
和QuerySingleAsync
以及它们相应的OrDefault
变体... QuerySingleOrDefaultAsync
的用法是:
await connection.QuerySingleOrDefaultAsync<short>(sql);
答案 1 :(得分:10)
您可以使用ExecuteScalarAsync
或Single()
使用ExecuteScalarAsync
,您可以使用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()
可以这种方式使用
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();
}
答案 2 :(得分:1)
您应该使用ExecuteScalar
:
status = await sqlConnection.ExecuteScalarAsync<short>("SELECT [StatusID] FROM [MyTable] WHERE [ID] = @ID", parameters, commandTimeout: _sqlCommandTimeoutInSeconds)