Yug*_*orf 3 .net dbnull field datareader vb.net-2010
我听说框架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)
Run Code Online (Sandbox Code Playgroud)
那些扩展方法涉及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);
Run Code Online (Sandbox Code Playgroud)
您当然可以将它们作为实用程序方法包装起来,也许就像您自己的自定义扩展方法一样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
}
Run Code Online (Sandbox Code Playgroud)
(抱歉使用c#作为示例 - 但你可以阅读c#比写出准确的 vb.net 更好)
| 归档时间: |
|
| 查看次数: |
2471 次 |
| 最近记录: |