SqlDataReader Best way to check for null values -sqlDataReader.IsDBNull vs DBNull.Value

前端 未结 3 484
盖世英雄少女心
盖世英雄少女心 2021-02-04 10:01

I want to retrieve decimal values from the database and I would like to know which is the recommended way to check for null values.

I have seen on MSDN - DBNull.Value F

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 10:51

    Here's a simpler version of @Karl Anderson's answer:

    public static class DbHelper
    {
        public static T GetValue(this SqlDataReader sqlDataReader, string columnName)
        {
            var value = sqlDataReader[columnName];
    
            if (value != DBNull.Value)
            {
                return (T)value;
            }
    
            return default(T);
        }
    }
    

    Or even:

    public static class DbHelper
    {
        public static T GetValue(this SqlDataReader sqlDataReader, string columnName)
        {
            var value = sqlDataReader[columnName];
    
            return value == DBNull.Value ? default(T) : (T) value;
        }
    }
    

    Direct casting seems to work just fine for either nullable or non-nullable types.

提交回复
热议问题