Guest User

Untitled

a guest
Dec 14th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. public static List<T> ToList<T>(this IDataReader dr)
  2. {
  3. var list = new List<T>();
  4. var obj = default(T);
  5. while (dr.Read())
  6. {
  7. obj = Activator.CreateInstance<T>();
  8. foreach (var prop in obj.GetType().GetProperties())
  9. {
  10. var columnDescription = getPropertyDescription(obj, prop.Name);
  11. if (existsDataReaderColumn(dr, columnDescription)) copyColumnValueToProperty(dr, obj, prop);
  12. }
  13. list.Add(obj);
  14. }
  15. return list;
  16. }
  17.  
  18. static void copyColumnValueToProperty<T>(IDataReader dr, T obj, PropertyInfo prop)
  19. {
  20. try
  21. {
  22. var columnDescription = getPropertyDescription(obj, prop.Name);
  23. var columnOrdinal = dr.GetOrdinal(columnDescription);
  24. var value = dr[columnOrdinal];
  25. var canBeNull = !prop.PropertyType.IsValueType || (Nullable.GetUnderlyingType(prop.PropertyType) != null);
  26. var castToType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
  27. if (canBeNull && value == null)
  28. prop.SetValue(obj, null, null);
  29. else
  30. prop.SetValue(obj, Convert.ChangeType(value, castToType, CultureInfo.InvariantCulture), null);
  31. }
  32. catch { }
  33. }
  34.  
  35. static bool existsDataReaderColumn(IDataReader dr, string propertyName)
  36. {
  37. try
  38. {
  39. var obj = dr[propertyName];
  40. return true;
  41. }
  42. catch { return false; }
  43. }
  44.  
  45. private static string getPropertyDescription(object value, string propname)
  46. {
  47. var propinfo = value.GetType().GetProperty(propname);
  48. var attributes =
  49. (OLAPMemberNameAttribute[])propinfo.GetCustomAttributes(
  50. typeof(OLAPMemberNameAttribute), false);
  51. if (attributes != null && attributes.Length > 0)
  52. return attributes[0].Description;
  53. else
  54. return value.ToString();
  55. }
Add Comment
Please, Sign In to add comment