Dapper - Get value of output parameter from stored procedure

1k views Asked by At

Without using Dapper, this code returns the correct result of "true":

using(connection= new SqlConnection(connectionString))
{
    using(var cmd = connection.CreateCommand())
    {
        cmd.CommandText= query;
        cmd.CommandType= CommandType.StoredProcedure;
        cmd.CommandTimeout = commandTimeout;

        var pDeviceId = new SqlParameter
        {
            ParameterName = "@DeviceId",
            DbType = DbType.String,
            Size = 150,
            Direction = ParameterDirection.Input,
            Value = parameter.DeviceId
        };
        cmd.Parameters.Add(pDeviceId);

        var pResponse = new SqlParameter
        {
            ParameterName = "@Response",
            DbType = DbType.Boolean,
            Direction = ParameterDirection.Output,
        };
        cmd.Parameters.Add(pResponse);

        await connection.OpenAsync();

        int i = cmd.ExecuteNonQuery();
        var response = (bool)cmd.Parameters["@Response"].Value;

        return response;
    }
}

But when using Dapper, I can't get this code to work. It always returns a value of "false":

using (connection = new SqlConnection(connectionString))
{
    using(var cmd = connection.CreateCommand())
    {
        var parameters = new DynamicParameters();
        parameters.Add("@DeviceId", parameter.DeviceId);
        parameters.Add("@Response", dbType: DbType.Boolean, direction: ParameterDirection.Output);

        var reply = (await connection.QueryAsync<bool>(
            query,
            param: parameters,
            commandType: System.Data.CommandType.StoredProcedure).ConfigureAwait(false)).FirstOrDefault();
        return reply;
    }
}
1

There are 1 answers

2
Yong Shun On BEST ANSWER

From here,

var reply = (await connection.QueryAsync<bool>(
            query,
            param: parameters,
            commandType: System.Data.CommandType.StoredProcedure).ConfigureAwait(false)).FirstOrDefault();

this will get the value from the SELECT statement from the stored procedure, but not the value from the Output parameter.

To get the value from the output parameter, you should do as below:

await connection.ExecuteAsync(
    query,
    param: parameters,
    commandType: System.Data.CommandType.StoredProcedure);

var reply = parameters.Get<bool>("@Response");

References

  1. Dapper/ProcedureTest.cs (TestDateTime2LosePrecisionInDynamicParameters method)

  2. Using Parameters With Dapper (Dapper Output Parameter section)