Setting NULL

I am trying to populate a class object with values ​​from a database table. The field someObject.Propertyis a type with a null type.

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

So, if SomeField- null, Convertwill give an error DBNull. Is there a special method I should use for this?

+5
source share
8 answers

This should work ...

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

@John- Good booty. Modify to reflect this supervision.

+5
source

This method may be useful for what you are trying to do. It will try to parse the column value in the corresponding type, and if it fails, it will return the default values ​​for the types.

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;
}
+3
source

, 0 . nullable, # null.

someObject.Property = (DBNull.Value.Equals(dbReader["SomeField"])) ? 0 : Convert.ToInt32(dbReader["SomeField"]);
+2

TryParse

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

You can also look using the zero coalescence operator ??to assign a default value if necessary.

+1
source

You can use TryParse. This will not specifically check for NULL, but it will tell you if it is a syntax method or not, which is probably what you really need.

bool result = Int32.TryParse(value, out number);
+1
source

You can use this:

if (reader["SomeField"] != DBNull.Value)
    someObject.Property = reader.GetInt32(dbReader("SomeField"));
0
source
int someFieldIndex = reader.GetOrdinal("SomeField");
someObject.Property = reader.IsDbNull(someFieldIndex) ? null : (Int32?)reader.GetInt32(someFieldIndex);
0
source
someObject.Property = Convert.ToInt32(dbReader["SomeField"].ToString()); 
0
source

All Articles