简体   繁体   English

Dapper 如何通过 DynamicParameter.Get 处理 DBNull

[英]Dapper How to Handle DBNull by DynamicParameter.Get

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

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

By referencing Dapper, I used the code above to call a Stored Procedure with an output parameter - MsgId.通过引用 Dapper,我使用上面的代码调用带有输出参数 - MsgId 的存储过程。 It is working fine, but in some cases, there would be no value returned from the Stored Procedure and the returned output parameter value would be null.它工作正常,但在某些情况下,存储过程不会返回任何值,并且返回的输出参数值将为空。 In these cases, I got this exception :在这些情况下,我得到了这个例外:

Attempting to cast a DBNull to a non nullable type!试图将 DBNull 转换为不可为空的类型! 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)请注意,在数据流完成之前(在 Query(..., buffered: false 的 'foreach' 之后,或在为 QueryMultiple 处理 GridReader 之后),输出/返回参数不会更新值

I'd understood that we could mark the return Data Type as nullable to avoid this error by using the code below我知道我们可以通过使用下面的代码将返回数据类型标记为可为空以避免此错误

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

But, is there any other way to check param.Get("MsgId") == null instead of using nullable data type - int?但是,有没有其他方法可以检查param.Get("MsgId") == null 而不是使用可为空的数据类型 - int?

Thanks Paulius, tried with dynamic datatype count = param.Get<dynamic>("MsgId");感谢 Paulius,尝试使用动态数据类型count = param.Get<dynamic>("MsgId"); and it work as what I'm looking for.它就像我正在寻找的那样工作。

In my case it was due to the Id parameter in stored proc was set as IN and at last, I was also setting its value to LAST_INSERT_ID() whereas in my C# (Dapper code) it was made ParameterDirection.InputOutput .在我的情况下,这是由于存储过程中的Id参数设置为IN ,最后,我还将其值设置为LAST_INSERT_ID()而在我的 C#(Dapper 代码)中,它被设置为ParameterDirection.InputOutput

After I made my stored proc ID as INOUT , the problem got resolved.在我将存储的过程 ID 设置为INOUT后,问题得到了解决。

In short what I understood was that the Id parameter behaviour (IN/OUT/INOUT) should be in sync at both the places ie in stored proc and C#.简而言之,我的理解是Id参数行为(IN/OUT/INOUT)应该在两个地方同步,即在存储过程和 C# 中。

您可以通过添加 nullable int 并强制转换为 int nullable 来处理绑定值 null 的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM