I need to fill a parameter in a SqlCommand
, but for some conditions I want to fill it with DBNull.Value
and otherwise with a value.
What I need is that when the variable truckID == -1
then put DBNull.Value
in the parameter, else put the value of truckID
in it.
This is what I have tried:
using (SqlCommand command = new SqlCommand(sql.ToString()))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@TruckID", truckID == -1 ? DBNull.Value : truckID);
but the compiler tells me :
Error CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'int'
If I would write this:
command.Parameters.AddWithValue("@TruckID", truckID == -1 ? 0 : truckID);
then the compiler is happy. So it seems that for a ternary operator both possible values must be of the same type.
What would be the best way to do this ?
EDIT:
the working code for me is this :
command.Parameters.Add
(new SqlParameter("@TruckID", SqlDbType.Int).Value = (import.TruckID == -1) ? (object)DBNull.Value : import.TruckID);
EDIT:
Actually the code above did not work after all.
At runtime I got this :
SqlParameterCollection only accepts non-null SqlParameter type objects, not DBNull objects
So I modified the code to this and that finally worked for me.
command.Parameters.Add
(new SqlParameter("@PlaceID", SqlDbType.Int) { Value = (import.TruckID == -1) ? (object)DBNull.Value : import.TruckID });