2012-02-27 68 views
2

我聽說框架4中有一個字段擴展方法,允許從數據讀取器接收空值,而不必經過第一次測試過程,如果不爲空然後...等等。這裏有關於擴展方法的信息(MSDN),但我不知道如何在代碼中使用它(對於.net而言是相對較新的,以前從未使用擴展方法)。如果有人能舉一個例子,我將不勝感激。使用datareader在.net4中的dbnull值

這是我試圖實現的,但是當任何一列中返回一個dbnull時它會返回一個錯誤。

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

回答

1

爲了使用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中時,您將會將整個閱讀器加載到內存中。如果您的行集很大,這可能會導致問題。

5

這些擴展方法涉及DataRow - 即DataTable ... IDataReader(等)。

double? val = reader.IsDBNull(index) ? (double?) null : reader.GetDouble(index); 
long? vol = reader.IsDBNull(index) ? (long?)null : reader.GetInt64(index); 

你當然可以換那些了作爲實用方法,也許對IDataReader自己的自定義擴展方法:在VB IIf,或C# - 你可以做你有條件想要的這裏,雖然

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)

+0

謝謝 - 很清楚。 – Yugmorf 2012-02-28 02:15:28