1

I get a row from table and some field of this row are null. How can I get these fields with SqlDataReader?

//so_type , so_read are null able 

while (reader.Read())
{
    s.id = (Int64)reader["so_id"];
    s.senderid = (Int64)reader["so_senderid"];
    s.body = (string)reader["so_body"];
    s.date = (string)reader["so_date"];
    s.isread = (bool)reader["so_read"];
    s.type = (int)reader["so_type"];
}
4

2 回答 2

2

您可以利用 C# 泛型编写一个辅助方法,该方法提取每个列的值或默认值,可以是null.

private static T GetValue<T>(object value)
{
    return value == DBNull.Value ? default(T) : (T) value;
}

while (reader.Read())
{
    s.id       = GetValue<long>(reader["so_id"]);
    s.senderid = GetValue<long>(reader["so_senderid"]);
    s.body     = GetValue<string>(reader["so_body"]);
    s.date     = GetValue<string>(reader["so_date"]);
    s.isread   = GetValue<bool>(reader["so_read"]);
    s.type     = GetValue<int>(reader["so_type"]);
}

这也假定该值已经是正确的类型。

更类型安全的实现将是:

private static T GetValue<T>(object value)
{
    return value == DBNull.Value
           ? default(T)
           : (T) Convert.ChangeType(value, typeof(T));
}
于 2013-07-07T04:14:49.533 回答
1

您可以使用IsDBNull 方法。像这样的东西:

int ordinal_so_type=reader.GetOrdinal("so_type");
//...
while(reader.Read()==true)
{
  //reading other columns here
  if (reader.IsDBNull(ordinal_so_type)==false)
  {
    s.type=reader.GetInt32(ordinal_so_type);
  }
  else
  {
    //do whatever you like if the so_type column is null
  }
}
于 2013-07-07T04:08:46.010 回答