[英]How to pass in nullable INT type to INSERT INTO parameter
I need to pass in a nullable int type (passed in as an OPTIONAL param, sometimes it's defined, sometimes it's not...) into an INSERT INTO command in C# via paramters. 我需要通过参数将可空的int类型(作为可选参数传入,有时是定义的,有时不是...)传递给C#中的INSERT INTO命令。 Below is a screenshot of my code.
下面是我的代码的屏幕截图。
Here is the offending line of code, truncated for clarity... 这是令人反感的代码行,为清楚起见被截断了...
public void WriteCustomColumns(... int? parentPlacementId = null)
{
command.Parameters["@ParentPlacementId"].Value = (parentPlacementId == null ? System.Data.SqlTypes.SqlInt32.Null.Value : parentPlacementId);
Here is the screenshot of the error... 这是错误的屏幕截图...
Try to not use the conditional operator 尝试不使用条件运算符
SqlParameter p = command.Parameters.Add("@ParentPlacementId", SqlDbType.BigInt);
if(parentPlacementId.HasValue)
p.Value = parentPlacementId;
else
p.Value = DBNull.Value;
As a possible alternative (not recommended) 作为一种可能的替代方法(不推荐)
command.Parameters["@ParentPlacementId"].Value =
(parentPlacementId.HasValue ? (object)parentPlacementId.Value : (object)DBNull.Value);
Your code is failing because System.Data.SqlTypes.SqlInt32.Null
throws SqlNullValueException
when you try to access .Value
. 您的代码失败,因为在尝试访问
.Value
时System.Data.SqlTypes.SqlInt32.Null
引发SqlNullValueException
。
Use just System.Data.SqlTypes.SqlInt32.Null
. 仅使用
System.Data.SqlTypes.SqlInt32.Null
。
Use: 采用:
command.Parameters["@ParentPlacementId"].Value = parentPlacementId.HasValue ? parentPlacementId.Value : System.Data.SqlTypes.SqlInt32.Null.Value;
Reference Microsoft's Using Nullable Type 参考Microsoft的使用Nullable类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.