DataExt.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Data;
  3. using System.Reflection;
  4. namespace Masuit.Tools.Database
  5. {
  6. /// <summary>
  7. /// SqlDataReader扩展类
  8. /// </summary>
  9. public static class DataExt
  10. {
  11. /// <summary>
  12. /// 根据DataRow映射到实体模型
  13. /// </summary>
  14. /// <typeparam name="T">实体模型</typeparam>
  15. /// <param name="row">数据行</param>
  16. /// <returns>映射后的实体模型</returns>
  17. public static T MapEntity<T>(this DataRow row) where T : class
  18. {
  19. T obj = Assembly.GetAssembly(typeof(T)).CreateInstance(typeof(T).FullName) as T;
  20. Type type = typeof(T);
  21. PropertyInfo[] properties = type.GetProperties();
  22. foreach (PropertyInfo p in properties)
  23. {
  24. p.SetValue(obj, row[p.Name]);
  25. }
  26. return obj;
  27. }
  28. /// <summary>
  29. /// 根据DataReader映射到实体模型
  30. /// </summary>
  31. /// <typeparam name="T">实体模型</typeparam>
  32. /// <param name="dr">IDataReader</param>
  33. /// <returns>映射后的实体模型</returns>
  34. public static T MapEntity<T>(this IDataReader dr) where T : class
  35. {
  36. T obj = Assembly.GetAssembly(typeof(T)).CreateInstance(typeof(T).FullName) as T;
  37. Type type = typeof(T);
  38. PropertyInfo[] properties = type.GetProperties();
  39. foreach (PropertyInfo p in properties)
  40. {
  41. p.SetValue(obj, dr[p.Name]);
  42. }
  43. return obj;
  44. }
  45. }
  46. }