c# - Dapper 如何通过 DynamicParameter.Get 处理 DBNull

标签 c# sql-server dapper

var param = new DynamicParameters();
param.Add("MsgId", DbType.Int32, direction: ParameterDirection.Output);

connection.Execute(MessageSelOutMessageId, param, commandType: CommandType.StoredProcedure);
count = param.Get<int>("MsgId");

通过引用 Dapper,我使用上面的代码调用了一个带有输出参数 - MsgId 的存储过程。它工作正常,但在某些情况下,存储过程不会返回任何值,并且返回的输出参数值为空。在这些情况下,我得到了这个异常(exception):

Attempting to cast a DBNull to a non nullable type! Note that out/return parameters will not have updated values until the data stream completes (after the 'foreach' for Query(..., buffered: false), or after the GridReader has been disposed for QueryMultiple)

我明白我们可以通过使用下面的代码将返回数据类型标记为可为空以避免此错误

count = param.Get<int?>("MsgId");

但是,有没有其他方法可以检查 param.Get("MsgId") == null 而不是使用可空数据类型 - int?

最佳答案

感谢 Paulius,尝试使用动态数据类型 count = param.Get<dynamic>("MsgId");它符合我的要求。

关于c# - Dapper 如何通过 DynamicParameter.Get 处理 DBNull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32856508/

相关文章:

.net - Sqlinq从linq创建sql查询的替代方法

wpf - 填充并绑定(bind)两个组合框 WPF Caliburn.micro

c# - 突出显示选定的 TreeNode

sql-server - 比较存储过程的两个版本

c# - 创建可在 LINQ (EF) 中使用的辅助方法

sql - 大表外键与小表外键

c# - Dapper 未能将 SQL uniqueidentifier 类型读取为字符串

c# - HttpResponseMessage' 不包含 'GetAwaiter' 的定义并且没有可访问的扩展方法 'GetAwaiter'

c# - 将 DataGrid 绑定(bind)到具有自定义对象类型列的 DataTable

C# 将函数作为参数传递