2012-02-27 5 views
2

프레임 워크 4에 필드 확장 방법이 있다는 것을 들었습니다. 그러면 네임이 아닌 경우 첫 번째 테스트 과정을 거치지 않고도 datareader에서 null 값을받을 수 있습니다. 등등 여기에 확장 방법에 대한 정보가 (MSDN),하지만 코드에서 사용하는 방법을 모르겠습니다 (상대적으로 .net에 익숙하지 않고 전에 확장 방법을 사용하지 않았습니다). 누군가가 예를들 수 있다면 감사하겠습니다..net4에서 dbnull 값을 사용하는 datareader를 사용합니다.

이것은 구현하려고 시도했지만 dbnull이 열 중 하나에서 반환되면 오류가 반환됩니다. DataRow 확장 방법을 사용하기 위해

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

답변

1

당신은 DataRow이 필요합니다. 거기에 DataReader에 아무런 방법이 없다, 그래서 당신이해야 할 것은 (C#으로)를 DataTable로 독자를로드하는 것입니다 :

var table = new DataTable(); 
table.Load(reader); 

foreach(DataRow row in table.Rows) 
{ 
    var value = row.Field<Decimal>(0); 
} 

DataReader를을 사용하여 논리적으로 동일 아니라는 것을 깨닫는 것이 중요하다. DataTable에로드 할 때 전체 판독기를 메모리에로드 할 때 Read() 메서드를 사용하십시오. 행 집합이 큰 경우 문제가 발생할 수 있습니다. 하지IDataReader (등) ... 즉 DataTable -

5

그 연장 DataRow 방법에 관한 것이다.

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

당신은 물론 IDataReader에 자신 만의 확장 방법으로 아마도, 유틸리티 방법으로 사람들을 마무리 할 수 ​​: C#에서 VB에서 IIf을, 또는 - 당신은하지만, 조건부 여기 원하는 것을 할 수 있습니다

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#을 사용 미안 -하지만 난 정확한 vb.net 쓸 수있는 것보다 당신은 아마 C#을 더 잘 읽을 수 있습니다)

+0

감사합니다 - 아주 명확. – Yugmorf

관련 문제