[英]SqlParameterCollection only accepts non-null SqlParameter type objects, not DBNull objects
When I add the SQL parameter p
to the collection I get an InvalidCastException
with the message from the post title. 当我将SQL参数
p
添加到集合时,我得到一个带有帖子标题消息的InvalidCastException
。
parentId
is a nullable integer and a nullable integer in the database. parentId
是可以为null的整数,并且是数据库中的可空整数。
Why do I get this exception and how can I solve it? 为什么我会得到这个例外,我该如何解决?
I do not use stored procedures and I have read the similar threads but they did not help me. 我不使用存储过程,我已经读过类似的线程,但他们没有帮助我。
var p = new SqlParameter("ParentId", SqlDbType.Int).Value = parentId ?? (object) DBNull.Value;
cmd.Parameters.Add(p);
You aren't adding your new SqlParameter
. 您没有添加
new SqlParameter
。 p
is the result of new SqlParameter("ParentId", SqlDbType.Int).Value = parentId ?? (object) DBNull.Value
p
是new SqlParameter("ParentId", SqlDbType.Int).Value = parentId ?? (object) DBNull.Value
new SqlParameter("ParentId", SqlDbType.Int).Value = parentId ?? (object) DBNull.Value
. new SqlParameter("ParentId", SqlDbType.Int).Value = parentId ?? (object) DBNull.Value
。 In other words, p
itself is DBNull.Value
. 换句话说,
p
本身就是DBNull.Value
。
Split the statement in two, like so: 将语句拆分为两个,如下所示:
var p = new SqlParameter("ParentId", SqlDbType.Int);
p.Value = parentId ?? (object) DBNull.Value;
cmd.Parameters.Add(p);
Alternatively, 或者,
var p = new SqlParameter("ParentId", SqlDbType.Int) { Value = parentId ?? (object) DBNull.Value };
cmd.Parameters.Add(p);
Either would make sure p
is the parameter, not the parameter's value. 要么确保
p
是参数,而不是参数的值。
你需要使用:
System.Data.SqlTypes.SqlInt32.Null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.