I\'m using a third party library which returns a data reader. I would like a simple way and as generic as possible to convert it into a List of objects.
For example, say
I found this solution.
var cmd = ctx.Connection.CreateCommand();
T result = DbDataReaderdHelper.Fill(cmd)
public static class DbDataReaderdHelper
{
public static List Fill(DbCommand dbCommand) where T : new()
{
List result = new List();
var reader = dbCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Type type = typeof(T);
T obj = (T)Activator.CreateInstance(type);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
var value = reader[property.Name];
try
{
if (value != null)
{
var convertedValue = TypeDescriptor.GetConverter(property.PropertyType).ConvertFromInvariantString(value.ToString());
property.SetValue(obj, convertedValue);
}
}
catch {}
}
result.Add(obj);
}
}
reader.Close();
return result;
}
}