views:

153

answers:

5

I got tired of writing the following code:

/* Commenting out irrelevant parts
public string MiddleName;
public void Save(){
    SqlCommand = new SqlCommand();
    // blah blah...boring INSERT statement with params etc go here. */
    if(MiddleName==null){
        myCmd.Parameters.Add("@MiddleName", DBNull.Value);
    }
    else{
        myCmd.Parameters.Add("@MiddleName", MiddleName);
    }
    /*
    // more boring code to save to DB.
}*/

So, I wrote this:

public static object DBNullValueorStringIfNotNull(string value)
{
    object o;
    if (value == null)
    {
        o = DBNull.Value;
    }
    else
    {
        o = value;
    }
    return o;
}

// which would be called like:
myCmd.Parameters.Add("@MiddleName", DBNullValueorStringIfNotNull(MiddleName));

If this is a good way to go about doing this then what would you suggest as the method name? DBNullValueorStringIfNotNull is a bit verbose and confusing.

I'm also open to ways to alleviate this problem entirely. I'd LOVE to do this:

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? DBNull.Value : MiddleName);

but that won't work because the "Operator '??' cannot be applied to operands of type 'string and 'System.DBNull'".

I've got C# 3.5 and SQL Server 2005 at my disposal if it matters.

+4  A: 

Cast either of your values to object and it will compile.

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? (object)DBNull.Value : MiddleName);
Adam Robinson
Sweet: `MiddleName ?? (object)DBNull.Value` works! Or better yet `public static readonly object DBNullValue = (object)DBNull.Value;` with `MiddleName ?? DBNullValue`! You are my hero.
David Murdoch
Argh, i have to wait 3 more minutes before I can accept your answer.
David Murdoch
@David: Nice! Hadn't even considered coalescing. I'll have to start doing that in my code. I thought about caching the value as you describe, but wanted to keep the code to one line.
Adam Robinson
16 more seconds and I can accept it.
David Murdoch
A: 

Yeap, we'd all love to do myCmd.Parameters.Add("@MiddleName", MiddleName ?? DBNull.Value);. Or better still, have the freakin' SqlClient layer understand that CLR null should be mapped to DBNull.Value when adding a parameter. Unfortunately the .Net type system closes the first alternative, and the implementation of SqlClient closes the second.

I'd go with a well known function name, like Coalesce or IsNull. Any DB developer will recognize what they do in an instant, from the name alone.

Remus Rusanu
There are good reasons that `null` doesn't map to `DBNull.Value`. Namely that it forces you to assign a value to every parameter, even if that "value" is a database null value.
Adam Robinson
Furthermore, having the ability to do string ?? DBNull.Value might be nice for this particular circumstance, you have to consider the issue from a compiler perspective: What is the return type of that expression? Should the compiler look for the most common ancestor, even if it's `object`?
Adam Robinson
Perhaps I wans't clear what I mean by 'the CLR type system': the impossibility to establish the compile time type of the expression `(type1 ?? type2)`. We're saying the same thing.
Remus Rusanu
@Remus: I love how you still have a Pony for your avatar.
David Murdoch
@David: Yea, I grabbed it and made it persistent :)
Remus Rusanu
+1  A: 

Personally this is what I would do with an extension method (make sure this goes into a static class)

public static object GetStringOrDBNull(this string obj)
{
    return string.IsNullOrEmpty(obj) ? DBNull.Value : (object) obj
}

Then you'd have

myCmd.Parameters.Add("@MiddleName", MiddleName.GetStringOrDBNull());
Chris Marisic
I do like the name. So +1 for that. I like the accepted answer's solution better though. :-)
David Murdoch
See if you change your mind after instead of having 100 if statements you have 100 ternary operators.
Chris Marisic
I'm actually using a null coalescing operator. You have to agree that `MiddleName ?? DBNullValue` is pretty darn easy. But +1 for your comment too.
David Murdoch
+1  A: 

I'd rather give you two totally different suggestions:

  1. Use an ORM. There are plenty of non-intrusive ORM tools.

  2. Write your own wrapper for building commands, with a cleaner interface. Something like:

    public class MyCommandRunner {
      private SqlCommand cmd;
    
    
      public MyCommandRunner(string commandText) {
        cmd = new SqlCommand(commandText);
      }
    
    
      public void AddParameter(string name, string value) {
        if (value == null)
         cmd.Parameters.Add(name, DBNull.Value);
        else
          cmd.Parameters.Add(name, value);
      }
    
    
      // ... more AddParameter overloads
    }
    

If you rename your AddParameter methods to just Add, you can use it in a very slick way:

var cmd = new MyCommand("INSERT ...")
  {
    { "@Param1", null },
    { "@Param2", p2 }
  };
Fábio Batista
+1 for this idea. I may consider this in the future.
David Murdoch
+1  A: 

I would suggest using nullable properties instead of public fields and an 'AddParameter' method (don't know if this code is optimized or correct, just off the top of my head):


private string m_MiddleName;

public string MiddleName
{
  get { return m_MiddleName; }
  set { m_MiddleName = value; }
}

.
.
.

public static void AddParameter(SQLCommand cmd, string parameterName, SQLDataType dataType, object value)
{
  SQLParameter param = cmd.Parameters.Add(parameterName, dataType);

  if (value is string) { // include other non-nullable datatypes
    if (value == null) {
      param.value = DBNull.Value;
    } else {
      param.value = value;
    }
  } else { // nullable data types
    if (value.HasValue) {
          param.value = value;
    } else {
          param.value = DBNull.Value;
    }
  }
}

.
.
.
AddParameter(cmd, "@MiddleName", SqlDbType.VarChar, MiddleName);