11/12/08

Technology ASP.NET


Cool Extension Methods for IDataReader Interface

I find it really annoying to use the GetOrdinal method of the DataReader class everytime I have to access data in a strongly typed manner using any of the Get[DataType] methods of the DataReader class. Have a look at below code:

int employeeID = dr.GetInt32(dr.GetOrdinal("EmployeeID"));
string firstName = dr.GetString(dr.GetOrdinal("FirstName"));
bool enabled = dr.GetBoolean(dr.GetOrdinal("Enabled"));

It would be so cool if I could directly specify the table column names like below:

int employeeID = dr.GetInt32("EmployeeID");
string firstName = dr.GetString("FirstName");
bool enabled = dr.GetBoolean("Enabled");

This would save me so much typing and make my code look so much cleaner. The power of Extension Methods make this possible :-) I created a new class named IDataReaderHelper which has 18 Extension Methods in all. You can simply pass the table column names instead of table column indexes to all these 18 Extension Methods, and these 18 Extension Methods would take care of the rest by calling the GetOrdinal method of the DataReader class internally :-). Have a look at the screen shot below:

Note: For readability purpose, above screen shot just highlights 3 of the 18 Extension Methods present in the IDataReaderHelper class. The 18 Extension Methods present in the IDataReaderHelper class are:

  • GetBoolean
  • GetByte
  • GetBytes
  • GetChar
  • GetChars
  • GetData
  • GetDataTypeName
  • GetDateTime
  • GetDecimal
  • GetDouble
  • GetFieldType
  • GetFloat
  • GetGuid
  • GetInt16
  • GetInt32
  • GetInt64
  • GetString
  • GetValue

You can find the entire source code for the IDataReaderHelper class as an attachment with this post available for download. To see all my posts on Extension Methods click here.

Update: Guys please dont forget to check out the Chris's comments (2nd from top) regarding performance issues when using the GetOrdinal method of the DataReader class inside a loop. Thanks for your excellent feedback Chris :-)

Update: Guys please dont forget to check out programatik's post here where he / she has compared performance (using GetOrdinal versus using int inside a loop). His / her post is in Portuguese so you can go to http://www.google.com/translate_t and translate programatik's post from Portuguese to English. It took me 30 minutes to figure out the language of this post ;-) Great work programatik ;-)

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

No comments: