I'm adding a parameter to be called with a MySQL stored procedure like
List<MySqlParameter> MyParams = new List<MySqlParameter>();
MyParams.Add(new MySqlParameter("MyId", 0));
But for some reason when I look at MyParams, MyId value when stepping through my code, it is converted to null. Does anyone know why this is because if I assign the value from a int variable like below it is fine
int id = 0;
List<MySqlParameter> MyParams = new List<MySqlParameter>();
MyParams.Add(new MySqlParameter("MyId", id));
Well, You fell into the corner case of c# that literal 0
can be converted to Enum
implicitly
An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type
Reference
So, new MySqlParameter("MyId", 0)
is compiled into MySqlParameter(string,MySqlDbType)
rather than MySqlParameter(string,object)
as the result your value 0
is ignored.
new MySqlParameter("MyId", id)
this works because implicit conversions to enum works only when the value is literal
not for variables
. So It is clear that this gets compiled into MySqlParameter(string,object)
resulting the expected results.
new MySqlParameter("MyId", (object)0)//this solves the problem
or this
New MySqlParameter("MyId", MySqlDbType.Int).Value = 0
BTW as @Suraj Singh pointed you may have to use @MyId
instead of MyId
.
Hope this helps
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 ---MSDN
Hope it's applicable for MySql
too.
MyParams.Add(New MySqlParameter("@MyId", MySqlDbType.int)).Value = 0;
or try
Parameters.AddWithValue("@MyId", 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With