3

我听说框架 4 中有一个字段扩展方法,它允许从数据读取器接收空值,而不必经过第一次测试 if not null then ... 等的过程。这里有关于扩展方法的信息(MSDN ),但我不知道如何在代码中使用它(对.net 来说相对较新,以前从未使用过扩展方法)。如果有人能举个例子,将不胜感激。

这是我试图实现的,但是当任一列中返回 dbnull 时,它都会返回错误。

Reader.Read()
Dim Val As Nullable(Of Double) = Reader.GetDecimal(0)
Dim Vol As Nullable(Of Long) = Reader.GetInt32(1)
4

2 回答 2

6

这些扩展方法与DataRow- 即DataTable......不是 IDataReader(等)有关。IIf不过,您可以在 VB 或 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# - 但您可能比我能写出准确的vb.net 更好地阅读 c#)

于 2012-02-27T12:03:53.810 回答
1

为了使用DataRow扩展方法,您需要一个DataRow. a 上没有方法DataReader,因此您需要做的是将阅读器加载到 a DataTable(在 C# 中):

var table = new DataTable();
table.Load(reader);

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

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

于 2012-02-27T12:03:47.803 回答