Output parameter is always null with multi.Read

泄露秘密 提交于 2019-12-07 05:21:45

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/13047896/output-parameter-is-always-null-with-multi-read

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!