如何使用Dapper从数据库中检索单个值

时间:2016-07-18 07:03:29

标签: c# .net sql-server asp.net-mvc dapper

我正在使用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返回单个值而不是集合吗?

3 个答案:

答案 0 :(得分:11)

仅供参考,Dapper现在已经添加了QuerySingleQuerySingleAsync以及它们相应的OrDefault变体... QuerySingleOrDefaultAsync的用法是:

await connection.QuerySingleOrDefaultAsync<short>(sql);

答案 1 :(得分:10)

您可以使用ExecuteScalarAsyncSingle() 使用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)