Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant form for assigning NULL to InsertCommand's NVarChar?

This code works for me very well:

if (someStr == null)
  da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = DBNull.Value;
else
  da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = someStr;

But my intuition tells me that there may be a one-liner version of it. Something like:

  da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = someStr==null ? DBNull.Value : someStr ;

But the one-liner I just posted above fails of course because DBNull.Value doesn't cast to String.

Is there a way to accomplish the one liner I so desire?

like image 314
scatmoi Avatar asked Dec 04 '22 14:12

scatmoi


2 Answers

You could cast someStr to an object

For example:

da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = someStr==null ? DBNull.Value : (object)someStr;

Or you could do as Oded and Servy suggested and use an extension method. While it may add a few lines of code it will save you from duplicate code.

As Servy pointed out, putting it on object could lead to clutter. For this reason I would put it on SqlParameter

public static void SetValue(this SqlParameter parameter, object value)
{
    parameter.Value = value == null ? DBNull.Value : value;
}

Then use it like so

da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).SetValue(someStr);
like image 162
cadrell0 Avatar answered Dec 28 '22 06:12

cadrell0


Create a function or extension method that will do the test and make the assignments as needed. Pass in someStr and the parameter name.

You will then be able to set the parameter in one line.

like image 31
Oded Avatar answered Dec 28 '22 08:12

Oded