我听说框架 4 中有一个字段扩展方法,允许从数据读取器接收空值,而不必经历第一次测试如果不为空则...等的过程。这里有关于扩展方法的信息(MSDN http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx),但我不知道如何在代码中使用它(我对 .net 相对较新,以前从未使用过扩展方法)。如果有人能举个例子,我将不胜感激。
这是我尝试实现的,但当任一列中返回 dbnull 时,它会返回错误。
Reader.Read()
Dim Val As Nullable(Of Double) = Reader.GetDecimal(0)
Dim Vol As Nullable(Of Long) = Reader.GetInt32(1)
这些扩展方法涉及DataRow
- i.e. DataTable
... not IDataReader
(ETC)。
不过,你可以在这里用条件做你想做的事 -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# 作为示例 - 但你读 C# 的能力可能比我写的更好accurate vb.net)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)