DataExt.cs 2.3 KB

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