null to DBNull in AddWithValue using object variable in C#

2.2k views Asked by At

I am trying to make the optional parameter of a C# Method to be converted to DBNull (if it is null) to be added with Parameter.AddWithValue method.

I saw many solutions (Set a database value to null with a SqlCommand + parameters), extension methods, etc, but i wanted a single line solution.

command.Parameters.AddWithValue("@Municipio", municipio ?? DBNull.Value)don't work (Operator '??' cannot be applied to operands of type 'string' and 'System.DBNull')

The method: public static void Foo(string bar, string municipio = null)

Unfortunately i can't do string municipio = DBNull.Value because "default parameter must be a compile-time constant" (what i don't exactly understand the meaning).

I was able to make it work as such:

object obj = municipio == null ? command.Parameters.AddWithValue("@Municipio", DBNull.Value) : command.Parameters.AddWithValue("@Municipio", municipio);

I am very uncomfortable with this, seems like a JavaScript way of doing, i want something like:

if municipio == null ? command.Parameters.AddWithValue("@Municipio", DBNull.Value) : command.Parameters.AddWithValue("@Municipio", municipio);

But somehow i am not being able to make it work like this, perhaps im missing some syntax (i tried many parenthesis/etc combinations).

So my question is, is it good practice the one-line solution i reached, or should i replace it?

1

There are 1 answers

3
gmdev86 On BEST ANSWER

Updated to handle if the variable is not initialized. Here is an example:

            OracleParameter P_COUNTYCODE = new OracleParameter("P_COUNTYCODE", OracleDbType.Varchar2);
            P_COUNTYCODE.Direction = ParameterDirection.Input;
            P_COUNTYCODE.Value = countyCode.Length > 0 ? countyCode : (object)DBNull.Value;

try:

command.Parameters.AddWithValue("@Municipio", !string.IsNullOrEmpty(municipio) > 0 ? municipio : (object)DBNull.Value)