SqlParameter with default value set to 0 doesn't work as expected

后端 未结 2 1634
醉酒成梦
醉酒成梦 2020-12-29 21:41

I was doing something like this:

SqlParameter param = new SqlParameter(\"@Param\", 0) { SqlDbType = SqlDbType.Int };

private void TestParam(SqlParameter par         


        
相关标签:
2条回答
  • 2020-12-29 22:25

    The 0 you are passing in is the type, not the value. 0 literals (and constant values) are allowed for any enum type - meaning the 0 of the underlying enum type, and are a better "match" than object, since it doesn't need boxing.

    Personally, I would use;

    Value = 0
    

    perhaps in the object initializer.

    0 讨论(0)
  • 2020-12-29 22:32

    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", Convert.ToInt32(0));
    

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

    Thanks Msdn :)

    0 讨论(0)
提交回复
热议问题