Introduction
This tip shows how to convert DataReader into IEnumerable
using C# through reflection.
Background
Converting DataReader
into IEnumerable
with C# can be useful in these scenarios:
- Working with LINQ and therefore with
IEnumberable
lists. - Working with ORM with Code First and getting data from Store Procedures.
Using the code
Step 1. To create Reflection method.
Parameters:
- One object to copy value property. Observe it's a reference value.
- Property Name/Value to set the object.
public class Reflection
{
public void FillObjectWithProperty(ref object objectTo, string propertyName, object propertyValue)
{
Type tOb2 = objectTo.GetType();
tOb2.GetProperty(propertyName).SetValue(objectTo, propertyValue);
}
}
Step 2. To create extension method
It is the most complex, we can find many information on Google about extension methods. The function is very detailed.
public static class IENumerableExtensions
{
public static IEnumerable<T> FromDataReader<T>(this IEnumerable<T> list, DbDataReader dr)
{
Reflection reflec = new Reflection();
Object instance;
List<Object> lstObj = new List<Object>();
while (dr.Read()){
instance= Activator.CreateInstance(list.GetType().GetGenericArguments()[0]);
foreach (DataRow drow in dr.GetSchemaTable().Rows){
reflec.FillObjectWithProperty(ref instance,
drow.ItemArray[0].ToString(), dr[drow.ItemArray[0].ToString()]);
}
lstObj.Add(instance);
}
List<t> lstResult = new List<t>();
foreach (Object item in lstObj){
lstResult.Add((T)Convert.ChangeType(item, typeof(T)));
}
return lstResult;
}
}</t></t>
Step 3. Sample of call extension method
T
: Any Generics Type. dr
: DataReader
List<T> list = new List<T>().FromDataReader(dr).ToList();