簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM