Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output parameter is always null with multi.Read

Tags:

c#

dapper

We are using Dapper.Net extensively and are very happy with it. However we have come across an issue when trying to retrieve output parameters from stored procedures using multi.Read:

var p = new DynamicParameters(); 
p.Add("@id", id); 
p.Add("TotalRows", dbType: DbType.Int32, direction: ParameterDirection.Output); 

using (var multi = cnn.QueryMultiple(string.Format("dbo.[{0}]", spName), p,
    commandType: CommandType.StoredProcedure))
{  
    int TotalRows = p.Get<int>("@TotalRows"); //This is always null

    var results = multi.Read<New_Supplier>().ToList<IDBSupplier>();
    var areas = multi.Read<node>().ToList<IDBNode>();
    var categories = multi.Read<node>().ToList<IDBNode>();
    int TotalRows = multi.Read<int>().FirstOrDefault(); // This works

}

However, if we use the connection.Query syntax to get a single resultset the output parameter is populated:

var result = cnn.Query<New_Supplier>(string.Format("spname"), p,
    commandType: CommandType.StoredProcedure).ToList<New_Supplier>();
int TotalRows = p.Get<int>("@TotalRows");

The error is that the sqlValue of AttachedParam on the output parameter in the Dapper DynamicParameters is always null.

To work around this we have added the value of the output parameter to the result sets of the stored procedure and are reading it that way.

Why is the parameter always null?

like image 740
Simon Avatar asked Oct 24 '12 11:10

Simon


1 Answers

In a TDS stream, the OUT parameters are at the end. In your Query<T> example, you have consumed the TDS stream:

var result = cnn.Query<New_Supplier>(string.Format("spname"), p,
    commandType: CommandType.StoredProcedure).ToList<New_Supplier>();
int TotalRows = p.Get<int>("@TotalRows");

so because you have consumed the stream, the new parameter values have been reached, and you should have the values available. In the QueryMultiple example, you have not reached the end of the TDS stream. Try moving the p.Get:

var p = new DynamicParameters(); 
p.Add("@id", id); 
p.Add("TotalRows", dbType: DbType.Int32, direction: ParameterDirection.Output); 

using (var multi = cnn.QueryMultiple(string.Format("dbo.[{0}]", spName), p,
    commandType: CommandType.StoredProcedure))
{      
    var results = multi.Read<New_Supplier>().ToList<IDBSupplier>();
    var areas = multi.Read<node>().ToList<IDBNode>();
    var categories = multi.Read<node>().ToList<IDBNode>();
}
int TotalRows = p.Get<int>("@TotalRows");

If that doesn't work, let me know ;p

like image 80
Marc Gravell Avatar answered Oct 28 '22 22:10

Marc Gravell