You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
3.3 KiB

1 year ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Reflection;
  6. namespace Common.Helper
  7. {
  8. public static class Mapper
  9. {
  10. public static IList<T> DataTableToClass<T>(DataTable Table) where T : class, new()
  11. {
  12. var dataList = new List<T>(Table.Rows.Count);
  13. Type classType = typeof(T);
  14. IList<PropertyInfo> propertyList = classType.GetProperties();
  15. if (propertyList.Count == 0)
  16. return new List<T>();
  17. List<string> columnNames = Table.Columns.Cast<DataColumn>().Select(column => column.ColumnName.ToLower()).ToList();
  18. try
  19. {
  20. foreach (DataRow dataRow in Table.AsEnumerable().ToList())
  21. {
  22. var classObject = new T();
  23. foreach (PropertyInfo property in propertyList)
  24. {
  25. if (property != null && property.CanWrite)
  26. {
  27. if (columnNames.Contains(property.Name.ToLower()))
  28. {
  29. if (dataRow[property.Name] != System.DBNull.Value)
  30. {
  31. object propertyValue = System.Convert.ChangeType(
  32. dataRow[property.Name],
  33. property.PropertyType
  34. );
  35. property.SetValue(classObject, propertyValue, null);
  36. }
  37. }
  38. }
  39. }
  40. dataList.Add(classObject);
  41. }
  42. return dataList;
  43. }
  44. catch
  45. {
  46. return new List<T>();
  47. }
  48. }
  49. public static T DataRowToClass<T>(DataRow row) where T : class, new()
  50. {
  51. Type classType = typeof(T);
  52. IList<PropertyInfo> propertyList = classType.GetProperties();
  53. if (propertyList.Count == 0)
  54. return new T();
  55. List<string> columnNames = row.Table.Columns.Cast<DataColumn>().Select(column => column.ColumnName.ToLower()).ToList();
  56. try
  57. {
  58. var classObject = new T();
  59. foreach (PropertyInfo property in propertyList)
  60. {
  61. if (property != null && property.CanWrite)
  62. {
  63. if (columnNames.Contains(property.Name.ToLower()))
  64. {
  65. if (row[property.Name] != System.DBNull.Value)
  66. {
  67. object propertyValue = System.Convert.ChangeType(
  68. row[property.Name],
  69. property.PropertyType
  70. );
  71. property.SetValue(classObject, propertyValue, null);
  72. }
  73. }
  74. }
  75. }
  76. return classObject;
  77. }
  78. catch
  79. {
  80. return new T();
  81. }
  82. }
  83. }
  84. }