5

我正在尝试使用数据库表中的值填充类对象。该someObject.Property字段是可为空的 int 类型。

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

所以,如果SomeFieldnullConvertDBNull报错。我应该为此使用特定的方法吗?

4

8 回答 8

5

这应该工作...

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

@John- 接得好。编辑以反映这种疏忽。

于 2011-05-19T16:58:00.100 回答
3

此方法可能对您尝试执行的操作很有用。它将尝试将列值解析为其各自的类型,如果不能,它将返回类型默认值。

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;
}
于 2011-05-19T17:05:10.513 回答
2

我使用它,替换0为任何默认值。如果属性是,nullable那么您将默认为 C# null

someObject.Property = (DBNull.Value.Equals(dbReader["SomeField"])) ? 0 : Convert.ToInt32(dbReader["SomeField"]);
于 2011-05-19T16:57:37.290 回答
1

TryParse

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

如果需要,您还可以查看使用 null 合并运算符??来提供默认值。

于 2011-05-19T16:58:05.140 回答
1

你可以使用TryParse. 这不会专门检查 NULL,但它会告诉您它是否可解析,这可能是您真正想要的。

bool result = Int32.TryParse(value, out number);
于 2011-05-19T16:58:48.260 回答
0

你可以使用这个:

if (reader["SomeField"] != DBNull.Value)
    someObject.Property = reader.GetInt32(dbReader("SomeField"));
于 2011-05-19T16:58:13.900 回答
0
int someFieldIndex = reader.GetOrdinal("SomeField");
someObject.Property = reader.IsDbNull(someFieldIndex) ? null : (Int32?)reader.GetInt32(someFieldIndex);
于 2011-05-19T17:00:17.557 回答
0
someObject.Property = Convert.ToInt32(dbReader["SomeField"].ToString()); 
于 2011-05-19T17:12:21.823 回答