Tuesday, March 1, 2011

Updating Nulls

Hello,

I am trying to generate a data layer template. When I do my Selects, Updates, and Inserts, the idea is to have the template work with all the columns because I don't know which one's contain values or not. The problem is that I may have an update statemtent like cmd.Parameters.AddWithValue("@Field", this.Field); and if that value is null, the query won't execute. How can I get around this problem?

UPDATE:

I tried the ?? solution but I receive the error Operator ?? cannot be applied to operands string(or int) and System.DBNull. It seems to only work if the field is actually null, but not if it has a value. Then I tried to place the type (object)DBNull in front of DBNull but still nothing.

Adding (object) to this field worked!

Thanks.

From stackoverflow
  • cmd.Parameters.AddWithValue("@Field", this.Field ?? DBNull.Value);
    

    ?? is the coalesce operator in C#.

    jumbojs : I've tried this but I receive the error Operator ?? cannot be applied to operands string(and int) and System.DBNull
    Wim Coenen : Try (object)this.Field ?? DBNull.Value
    jumbojs : Hey thanks to all. That worked!

0 comments:

Post a Comment