SqlParameterCollection only accepts non-null SqlParameter type objects, not DBNull objects

Elisabeth picture Elisabeth · Nov 30, 2012 · Viewed 16.2k times · Source

When I add the SQL parameter p to the collection I get an InvalidCastException with the message from the post title.

parentId is a nullable integer and a nullable integer in the database.

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);  

Answer

user743382 picture user743382 · Nov 30, 2012

You aren't adding your new SqlParameter. p is the result of new SqlParameter("ParentId", SqlDbType.Int).Value = parentId ?? (object) DBNull.Value. In other words, p itself is 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.