Pregunta

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?

¿Fue útil?

Solución

This should work...

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

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

Otros consejos

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;
}

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"]);

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.

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);
someObject.Property = Convert.ToInt32(dbReader["SomeField"].ToString()); 
int someFieldIndex = reader.GetOrdinal("SomeField");
someObject.Property = reader.IsDbNull(someFieldIndex) ? null : (Int32?)reader.GetInt32(someFieldIndex);

You can use this:

if (reader["SomeField"] != DBNull.Value)
    someObject.Property = reader.GetInt32(dbReader("SomeField"));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top