A Type Safe IDataReader Wrapper


I don’t always use NHibernate… it’s true… in fact, plain old ADO.NET, DataSets, DataTables and IDataReaders can offer some nice advantages when used in the right way at the right time. Today, I found myself writing more IDataReader code and getting tired of having to get the ordinal, check for dbnull, and then retrieve the data. So, I wrote a quick wrapper around that functionality, giving me the specific types of data that I want based on my column name. I know this has been done a thousand times before, but I wanted to share anyways. It’s not “complete” if you’re looking for all of the IDataReader functionality. It fills my current needs, though, and is easy to extend when you need to.

   1: public class TypeSafeDataReaderWrapper

   2: {

   3:     private readonly IDataReader dataReader;

   4:  

   5:     public TypeSafeDataReaderWrapper(IDataReader dataReader)

   6:     {

   7:         this.dataReader = dataReader;

   8:     }

   9:  

  10:     public bool GetBoolean(string columnName)

  11:     {

  12:         return GetValue<bool>(columnName);

  13:     }

  14:  

  15:     public int GetInt32(string columnName)

  16:     {

  17:         return GetValue<int>(columnName);

  18:     }

  19:  

  20:     public string GetString(string columnName)

  21:     {

  22:         return GetValue<string>(columnName);

  23:     }

  24:  

  25:     public decimal GetDecimal(string columnName)

  26:     {

  27:         return GetValue<decimal>(columnName);

  28:     }

  29:  

  30:     private T GetValue<T>(string columnName)

  31:     {

  32:         T value = default(T);

  33:         int columnIndex = dataReader.GetOrdinal(columnName);

  34:         if (columnIndex > -1)

  35:         {

  36:             if (!dataReader.IsDBNull(columnIndex))

  37:             {

  38:                 value = (T) dataReader.GetValue(columnIndex);

  39:             }

  40:         }

  41:         return value;

  42:     }

  43: }

</div> </div>

Semantic Code: Migrating From A Chatty Interface To A Simple One With A Data Transfer Object