【问题标题】:Output parameter is always null with multi.Read使用 multi.Read 时,输出参数始终为空
【发布时间】:2012-10-14 09:57:57
【问题描述】:

我们正在广泛使用Dapper.Net,并且对此非常满意。但是,我们在尝试使用 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

}

但是,如果我们使用 connection.Query 语法来获取单个结果集,则会填充输出参数:

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

错误是Dapper DynamicParameters中输出参数上AttachedParam的sqlValue总是为null。

为了解决这个问题,我们将输出参数的值添加到存储过程的结果集中,并以这种方式读取它。

为什么参数总是为空?

【问题讨论】:

    标签: c# dapper


    【解决方案1】:

    在 TDS 流中,OUT 参数在末尾​​em>。在您的 Query&lt;T&gt; 示例中,您使用了 TDS 流

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

    因此,因为您已经消费了流,所以已经达到了新的参数值,并且您应该有可用的值。在QueryMultiple 示例中,您尚未到达 TDS 流的末尾。尝试移动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");
    

    如果 那个 不起作用,请告诉我;p

    【讨论】:

    • 谢谢马克,它有效。我知道它必须是一些简单的东西,但就是看不到它......
    • @Simon 现在可能很明显,但要补充一点:直接使用 ADO.NET 时会得到完全相同的行为。
    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    相关资源
    最近更新 更多