Why does the SqlParameter name/value constructor treat 0 as null?

我只是一个虾纸丫 提交于 2019-11-27 14:36:12

As stated in the documentation for that constructor:

When you specify an Object in the value parameter, the SqlDbType is inferred from the Microsoft .NET Framework type of the Object.

Use caution when you use this overload of the SqlParameter constructor to specify integer parameter values. Because this overload takes a value of type Object, you must convert the integral value to an Object type when the value is zero, as the following C# example demonstrates.

Parameter = new SqlParameter("@pname", (object)0);

If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameter (string, SqlDbType) constructor overload.

You simply were calling a different constructor than you thought in your case.

The reason for this is that C# allows an implicit conversion from the integer literal 0 to enum types (which are just integral types underneath), and this implicit conversion causes the (string, SqlDbType) constructor to be a better match for overload resolution than the boxing conversion necessary to convert int to object for the (string, object) constructor.

This will never be a problem when you pass an int variable, even if the value of that variable is 0 (because it is not a zero literal), or any other expression that has the type int. It will also not happen if you explicitly cast the int to object as seen above, because then there is only one matching overload.

It is good practices to use typed data while passing/adding your parameters.

Below way you can accomplish the task as below:

For string/varchar typed data:

SqlParameter pVarchar = new SqlParameter
                    {
                        ParameterName = "Test",
                        SqlDbType = System.Data.SqlDbType.VarChar,
                        Value = string.Empty,
                    };

For int typed data:

SqlParameter pInt = new SqlParameter
                    {
                        ParameterName = "Test",
                        SqlDbType = System.Data.SqlDbType.Int,
                        Value = 0,
                    };

You can change the value of SqlDbType according to your used data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!