How to auto map DbDataReader to List

This is a code example to simplify mapping fields from DbDataReader to IList

How to Use It!
 
DbDataReader reader = cmd.ExecuteReader();  
var results = DbReaderUtil.FetchRows(this, reader);  
The Code
 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Reflection;

public  class DbReaderUtil 
{

     public static IList FetchRows(Type t, DbDataReader reader)  
     {  
       Type t_list = typeof(List<>).MakeGenericType(t);  
       IList list =(IList) Activator.CreateInstance(t_list);  
       var properties = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);  
       while (reader.Read())  
       {  
         var item = Activator.CreateInstance(t);  
         for (int i = 0; i < reader.FieldCount; i++)                      
          {                          

           string ordinalName = reader.GetName(i);                          
           var prop = properties.FirstOrDefault(x => x.Name == ordinalName);  
           if (prop != null)  
           {  
             try  
             {  
               if (!reader.IsDBNull(i))  
               {  
                 object val = reader.GetValue(i);  
                 object value = null;  
                 try  
                 {  
                   value = Convert.ChangeType(val, prop.PropertyType);  
                 }  
                 catch (Exception)  
                 {  
                   if (val != null)  
                   {  
                     value = val.ToString();  
                   }  
                 }  
                 if (value != null)  
                 {  
                   prop.SetValue(item, value);  
                 }  
               }  
             }  
             catch (Exception)  
             {  
             }  
           }  
         }  
         list.Add(item);  
       }  
       return list;  
     }  
}
Advertisements