[英]using datareader with dbnull values in .net4
我听说框架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更好)
要使用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
时,将整个读取器加载到内存中。 如果您的行集很大,这可能会导致问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.