Finding null value in Dataset - DataRow.IsNull method vs ==DbNull.Value - c#

后端 未结 5 621
夕颜
夕颜 2021-01-01 20:32

What are the benefits of using the c# method DataRow.IsNull to determine a null value over checking if the row equals DbNull.value?

if(ds.Tables[0].Rows[0].I         


        
5条回答
  •  春和景丽
    2021-01-01 21:03

    FWIW, I wrote a bunch of DataRow extension methods — CastAsXXX() — to avoid having to deal with DB nullability...or at least defer it a bit B^). Here's my CastAsInt() and CastAsIntNullable() methods:

    #region downcast to int
    
    public static int CastAsInt( this DataRow row , int index )
    {
      return toInt( row[index] ) ;
    }
    public static int CastAsInt( this DataRow row , string columnName )
    {
      return toInt( row[columnName] ) ;
    }
    
    public static int? CastAsIntNullable( this DataRow row , int index )
    {
      return toIntNullable( row[index] );
    }
    public static int? CastAsIntNullable( this DataRow row , string columnName )
    {
      return toIntNullable( row[columnName] ) ;
    }
    
    #region conversion helpers
    
    private static int toInt( object o )
    {
      int value = (int)o;
      return value;
    }
    
    private static int? toIntNullable( object o )
    {
      bool hasValue = !( o is DBNull );
      int? value    = ( hasValue ? (int?) o : (int?) null ) ;
      return value;
    }
    
    #endregion conversion helpers
    
    #endregion downcast to int
    

    Usage is pretty straightforward. You just need to state your expectations up front.

    DataRow dr = GetADataRowFromSomewhere() ;
    // Throws NullReferenceException if the column is null
    int     x  = dr.CastAsInt(         "column_1" ) ;
    // Is perfectly happy with nulls (as it should be)
    int?    y  = dr.CastAsIntNullable( "column_1" ) ;
    

    I tried to make them generic, but no dice unless I'm willing to correlate NULLs from the database with the default value for the type (e.g., 0 for numeric types), which I'm not.

提交回复
热议问题