如何使用具有空值的datareader

Ant*_*ony 7 c# null datareader

说我有这个班:

class myclass
{
    public int Field1{ get; set; }
    public int? Field2 { get; set; } //Note Field2 is nullable
 }
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用来自数据库的数据填充通用列表.由于GetSqlInt32实现了INullable,我认为下面的代码可以工作.它没有.如果Field2为null,则会生成错误.

List<myclass> mylist=new List<myclass>();

int Field1_Ordinal = rdr.GetOrdinal("Field1");
int Field2_Ordinal = rdr.GetOrdinal("Field2");

SqlDataReader rdr = cmd.ExecuteReader(); //Execute a stored procedure to retrieve data from the database

while (rdr.Read())
 {
   mylist.Add(new myclass
   {
      Field1 = rdr.GetSqlInt32(Field1_Ordinal).Value,
      Field2 = rdr.GetSqlInt32(Field2_Ordinal).Value  //Error if field2 is null
   });
 }
Run Code Online (Sandbox Code Playgroud)

任何想法为什么它不起作用?

Jon*_*eet 24

在我看来,你需要这样的转换(为方便起见使用扩展方法):

public static int? ToNullableInt32(this SqlInt32 value)
{
    return value.IsNull ? (int?) null : value.Value;
}
Run Code Online (Sandbox Code Playgroud)

然后:

Field2 = rdr.GetSqlInt32(Field2_Ordinal).ToNullableInt32()
Run Code Online (Sandbox Code Playgroud)

(评论其他答案:没有必要DbNull加入这个,因为SqlInt32已经可以代表空值.你只需要在使用前检测它Value.)


Ign*_*cia 6

看看这个不是我写的解决方案:

employee.FirstName = sqlreader[indexFirstName] as string;
employee.Age = sqlreader[indexAge] as int? ?? default(int);
Run Code Online (Sandbox Code Playgroud)

它最初是在这里提出的:

SQL数据读取器 - 处理空列值