I like to use DataTable , not DataReader . I hate repeating the pattern, so I added some extension methods for the DataRow class to encapsulate the downstream logic and make the code more readable:
DataTable dt = ExecStoredProcedure() ; foreach ( DataRow dr in dt ) { int id = dr.CastAsInt("id") ; dateTime? dtLastUpdated = dr.CastAsDateTimeNullable("last_update_date") ; int? col3 = dr.CastASIntNullable(3) ; }
Here is the code to lower the column value from DataRow to int / int? :
#region downcast to int public static int CastAsInt( this DataRow row , int index ) { return toInt( row[index] ) ; } public static int CastAsInt( this DataRow row , string columnName ) { return toInt( row[columnName] ) ; } public static int? CastAsIntNullable( this DataRow row , int index ) { return toIntNullable( row[index] ); } public static int? CastAsIntNullable( this DataRow row , string columnName ) { return toIntNullable( row[columnName] ) ; }
I am sure that similar extension methods with DataReader will be quite simple.
Nicholas carey
source share