在.NET 4中使用DataReader处理DBNull值

3
我听说在框架4中有一个领域扩展方法,允许从数据读取器接收空值,而无需首先测试是否为null,然后再进行处理。 这里有关于扩展方法的信息(MSDN),但是我不知道如何在代码中使用它(相对较新于.net且从未使用过扩展方法)。 如果有人能给出示例,将不胜感激。
这是我尝试实现的内容,但当返回dbnull时会返回错误。
Reader.Read()
Dim Val As Nullable(Of Double) = Reader.GetDecimal(0)
Dim Vol As Nullable(Of Long) = Reader.GetInt32(1)
2个回答

6
这些扩展方法与 DataRow 相关,即与 DataTable 相关,而不是与 IDataReader (等等)相关。您可以在此处使用条件进行操作,例如在 VB 中使用 IIf,或在 C# 中:
double? val = reader.IsDBNull(index) ? (double?) null : reader.GetDouble(index);
long? vol = reader.IsDBNull(index) ? (long?)null : reader.GetInt64(index);

当然,你可以将这些内容封装为实用方法,可能是作为自己的自定义扩展方法在IDataReader上:

public static class DataReaderExtensions
{
    public static int? ReadNullableInt32(this IDataReader reader, int index)
    {
        return reader.IsDBNull(index) ? (int?)null : reader.GetInt32(index);
    }
    public static long? ReadNullableInt64(this IDataReader reader, int index)
    {
        return reader.IsDBNull(index) ? (long?)null : reader.GetInt64(index);
    }
    public static double? ReadNullableDouble(this IDataReader reader, int index)
    {
        return reader.IsDBNull(index) ? (double?)null : reader.GetDouble(index);
    }
    public static string ReadNullableString(this IDataReader reader, int index)
    {
        return reader.IsDBNull(index) ? null : reader.GetString(index);
    }
    // etc
}

对于使用C#示例我感到抱歉,但是您可能比我更能够读懂C#而不是我写的精确的VB.NET。


1
为了使用DataRow扩展方法,您需要一个DataRow。DataReader上没有方法,因此您需要将读取器加载到DataTable中(在C#中):
var table = new DataTable();
table.Load(reader);

foreach(DataRow row in table.Rows)
{
    var value = row.Field<Decimal>(0);
}

重要的是要意识到,这与使用DataReader.Read()方法在逻辑上并不等价,因为当您将其加载到DataTable中时,您将会将整个读取器加载到内存中。如果您的行集很大,这可能会导致问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接