Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a NULL value

Tags:

c#

dbnull

I'm trying to populate a class object with values from a database table. The someObject.Property field is a nullable int type.

someObject.Property = Convert.ToInt32(dbReader["SomeField"]);

So, if SomeField is null, Convert will give a DBNull error. Is there a specific method I should be using for this?

like image 702
StoneJedi Avatar asked May 19 '11 16:05

StoneJedi


2 Answers

This should work...

someObject.Property = dbReader["SomeField"].Equals(DBNull.Value)
    ? null
    : (Int32)dbReader["SomeField"];

@John - Good catch. Edit to reflect that oversight.

like image 196
Yuck Avatar answered Sep 20 '22 18:09

Yuck


This method may be useful for what you're trying to do. It will try and parse the column value into it's respective type, and if it can't it will the return the types default value.

public T ParseValue<T>(System.Data.SqlClient.SqlDataReader reader, string column)
{
     T result = default(T);
     int index = reader.GetOrdinal(column);
     if (!reader.IsDBNull(index))
         result = (T)reader.GetValue(index);

     return result;
}
like image 21
Iain Ward Avatar answered Sep 22 '22 18:09

Iain Ward