开发者

Casting a NULL value

开发者 https://www.devze.com 2023-03-07 06:09 出处:网络
I\'m trying to populate a class object with values from a database table. The someObject.Property field is a nullable int type.

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["SomeFiel开发者_Python百科d"]);

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


This should work...

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

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


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

精彩评论

暂无评论...
验证码 换一张
取 消