I like to use DataTable
rather than a DataReader
. I hate repetitive boilerplate, so I added some extension methods to to the DataRow
class to encapsulate the downcast logic and make for more readable code:
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 the code for the downcasting a column value from a DataRow
to an 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] ) ;
}
#region conversion helpers
private static int toInt( object o )
{
int value = (int)o;
return value;
}
private static int? toIntNullable( object o )
{
bool hasValue = !( o is DBNull );
int? value = ( hasValue ? (int?) o : (int?) null ) ;
return value;
}
#endregion conversion helpers
#endregion downcast to int
I sure hanging similar extension methods off a DataReader would be fairly simple.