5

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?

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
StoneJedi
  • 575
  • 1
  • 8
  • 19

8 Answers8

5

This should work...

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

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

Yuck
  • 49,664
  • 13
  • 105
  • 135
3

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;
}
Iain Ward
  • 9,850
  • 5
  • 34
  • 41
2

I use this, replacing 0 with whatever default. If the property is nullable then you would default to the C# null.

someObject.Property = (DBNull.Value.Equals(dbReader["SomeField"])) ? 0 : Convert.ToInt32(dbReader["SomeField"]);
Dustin Laine
  • 37,935
  • 10
  • 86
  • 125
  • His property is an `Int32?` so probably `null` is preferred. Otherwise same idea. =) – Yuck May 19 '11 at 16:58
  • Whoops, missed that in your post. He did state "The someObject.Property field is a nullable int type." – Yuck May 19 '11 at 17:01
1

There is TryParse

http://msdn.microsoft.com/en-us/library/f02979c7.aspx

You can also look at using the null coalescing operator ?? to give a default value if needed.

manojlds
  • 290,304
  • 63
  • 469
  • 417
1

You could use TryParse. This won't specifically check for NULLs but it will tell you whether it is parseable or not which is probably what you really want.

bool result = Int32.TryParse(value, out number);
manojlds
  • 290,304
  • 63
  • 469
  • 417
Joe Phillips
  • 49,743
  • 32
  • 103
  • 159
0

You can use this:

if (reader["SomeField"] != DBNull.Value)
    someObject.Property = reader.GetInt32(dbReader("SomeField"));
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Akrem
  • 5,033
  • 8
  • 37
  • 64
0
int someFieldIndex = reader.GetOrdinal("SomeField");
someObject.Property = reader.IsDbNull(someFieldIndex) ? null : (Int32?)reader.GetInt32(someFieldIndex);
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Nitin Midha
  • 2,258
  • 20
  • 22
0
someObject.Property = Convert.ToInt32(dbReader["SomeField"].ToString()); 
Nighil
  • 4,099
  • 7
  • 30
  • 56