What is the best way to deal with DBNull's

后端 未结 14 1038
迷失自我
迷失自我 2020-12-02 15:45

I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this:



        
14条回答
  •  孤城傲影
    2020-12-02 16:06

    Brad Abrams posted something related just a couple of days ago http://blogs.msdn.com/brada/archive/2009/02/09/framework-design-guidelines-system-dbnull.aspx

    In Summary "AVOID using System.DBNull. Prefer Nullable instead."

    And here is my two cents (of untested code :) )

    // Or if (row["fooColumn"] == DBNull.Value)
    if (row.IsNull["fooColumn"])
    {
       // use a null for strings and a Nullable for value types 
       // if it is a value type and null is invalid throw a 
       // InvalidOperationException here with some descriptive text. 
       // or dont check for null at all and let the cast exception below bubble  
       value = null;
    }
    else
    {
       // do a direct cast here. dont use "as", "convert", "parse" or "tostring"
       // as all of these will swallow the case where is the incorect type.
       // (Unless it is a string in the DB and really do want to convert it)
       value = (string)row["fooColumn"];
    }
    

    And one question... Any reason you are not using an ORM?

提交回复
热议问题