加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在.net4中使用带有dbnull值的datareader

发布时间:2020-12-17 07:10:32 所属栏目:百科 来源:网络整理
导读:我听说框架4中有一个字段扩展方法允许一个接收来自datareader的空值,而不必经过第一次测试的过程,如果不是null那么……等等.这里有关于扩展方法的信息( MSDN) ),但我不知道如何在代码中使用它(相对较新的.net和以前从未使用过的扩展方法).如果有人能举一个例
我听说框架4中有一个字段扩展方法允许一个接收来自datareader的空值,而不必经过第一次测试的过程,如果不是null那么……等等.这里有关于扩展方法的信息( MSDN) ),但我不知道如何在代码中使用它(相对较新的.net和以前从未使用过的扩展方法).如果有人能举一个例子,我将不胜感激.

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

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

解决方法

这些扩展方法涉及DataRow – 即DataTable ……而不是IDataReader(etc).
你可以用条件来做你想要的事情 – 虽然在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更好)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读