Skip to content

Instantly share code, notes, and snippets.

@lluisfranco
Last active December 12, 2017 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lluisfranco/11f8cc57df849049b36426eb027edb6d to your computer and use it in GitHub Desktop.
Save lluisfranco/11f8cc57df849049b36426eb027edb6d to your computer and use it in GitHub Desktop.
public static List<T> ToList<T>(this IDataReader dr)
{
var list = new List<T>();
var obj = default(T);
while (dr.Read())
{
obj = Activator.CreateInstance<T>();
foreach (var prop in obj.GetType().GetProperties())
{
var columnDescription = getPropertyDescription(obj, prop.Name);
if (existsDataReaderColumn(dr, columnDescription)) copyColumnValueToProperty(dr, obj, prop);
}
list.Add(obj);
}
return list;
}
static void copyColumnValueToProperty<T>(IDataReader dr, T obj, PropertyInfo prop)
{
try
{
var columnDescription = getPropertyDescription(obj, prop.Name);
var columnOrdinal = dr.GetOrdinal(columnDescription);
var value = dr[columnOrdinal];
var canBeNull = !prop.PropertyType.IsValueType || (Nullable.GetUnderlyingType(prop.PropertyType) != null);
var castToType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
if (canBeNull && value == null)
prop.SetValue(obj, null, null);
else
prop.SetValue(obj, Convert.ChangeType(value, castToType, CultureInfo.InvariantCulture), null);
}
catch { }
}
static bool existsDataReaderColumn(IDataReader dr, string propertyName)
{
try
{
var obj = dr[propertyName];
return true;
}
catch { return false; }
}
private static string getPropertyDescription(object value, string propname)
{
var propinfo = value.GetType().GetProperty(propname);
var attributes =
(OLAPMemberNameAttribute[])propinfo.GetCustomAttributes(
typeof(OLAPMemberNameAttribute), false);
if (attributes != null && attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment