Handle DBNull in C#

前端 未结 13 661
梦谈多话
梦谈多话 2020-11-30 01:36

Is there a better/cleaner way to do this?

int stockvalue = 0;
if (!Convert.IsDBNull(reader[\"StockValue\"]))
    stockvalue = (int)reader[\"StockValue\"];


        
相关标签:
13条回答
  • 2020-11-30 02:11

    I wrote an extension method several days ago. By using it you could just do:

    int? stockvalue = reader.GetValue<int?>("StockValue");
    

    Here's the extension method (modify to fit your needs):

    public static class ReaderHelper
    {
        public static bool IsNullableType(Type valueType)
        {
            return (valueType.IsGenericType &&
                valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
        }
    
        public static T GetValue<T>(this IDataReader reader, string columnName)
        {
            object value = reader[columnName];
            Type valueType = typeof(T);
            if (value != DBNull.Value)
            {
                if (!IsNullableType(valueType))
                {
                    return (T)Convert.ChangeType(value, valueType);
                }
                else
                {
                    NullableConverter nc = new NullableConverter(valueType);
                    return (T)Convert.ChangeType(value, nc.UnderlyingType);
                }
            }
            return default(T);
        }
    }
    
    0 讨论(0)
  • 2020-11-30 02:11

    use the Nullable<int> type...int? for short

    0 讨论(0)
  • 2020-11-30 02:13
    int stockvalue = reader["StockValue"] != DbNull.Value ? Convert.ToInt32(reader["StockValue"]) : 0;
    
    0 讨论(0)
  • 2020-11-30 02:15
    int? stockvalue = (int?)(!Convert.IsDBNull(result) ? result : null);
    

    One possible solution so that you ensure that the DBNull carries across to your code. For our group, as a best practice, we try and not allow NULL columns in the database unless its really needed. There is more overhead in coding to handle it, and sometimes just rethinking the problem makes it so its not required.

    0 讨论(0)
  • 2020-11-30 02:17

    I have two following extension methods in my project:

        public static T GetValueSafe<T>(this IDataReader dataReader, string columnName, Func<IDataReader, int, T> valueExtractor)
            where T : class 
        {
            T value;
            if (dataReader.TryGetValueSafe(columnName, valueExtractor, out value))
            {
                return value;
            }
    
            return null;
        }
    
        public static bool TryGetValueSafe<T>(this IDataReader dataReader, string columnName, Func<IDataReader, int, T> valueExtractor, out T value)
        {
            int ordinal = dataReader.GetOrdinal(columnName);
    
            if (!dataReader.IsDBNull(ordinal))
            {
                // Get value.
                value = valueExtractor.Invoke(dataReader, ordinal);
    
                return true;
            }
    
            value = default(T);
            return false;
        }
    

    The usage can be like this:

    string companyName = dataReader.GetValueSafe("CompanyName", (reader, ordinal) => reader.GetString(ordinal));
    
    0 讨论(0)
  • 2020-11-30 02:18

    Here's one way.

    int stockvalue = Convert.IsDbNull(reader["StockValue"]) ? 0 : (int)reader["StockValue"];
    

    You could also use TryParse

    int stockvalue = 0
    Int32.TryParse(reader["StockValue"].ToString(), out stockvalue);
    

    Let us know which way works for you

    0 讨论(0)
提交回复
热议问题