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.

56 lines
2.0 KiB

4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Repository.DAO
  9. {
  10. public static class Mapper
  11. {
  12. public static IList<T> DataTableToClass<T>(DataTable Table) where T : class, new()
  13. {
  14. var dataList = new List<T>(Table.Rows.Count);
  15. Type classType = typeof(T);
  16. IList<PropertyInfo> propertyList = classType.GetProperties();
  17. if (propertyList.Count == 0)
  18. return new List<T>();
  19. List<string> columnNames = Table.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToList();
  20. try
  21. {
  22. foreach (DataRow dataRow in Table.AsEnumerable().ToList())
  23. {
  24. var classObject = new T();
  25. foreach (PropertyInfo property in propertyList)
  26. {
  27. if (property != null && property.CanWrite)
  28. {
  29. if (columnNames.Contains(property.Name))
  30. {
  31. if (dataRow[property.Name] != System.DBNull.Value)
  32. {
  33. object propertyValue = System.Convert.ChangeType(
  34. dataRow[property.Name],
  35. property.PropertyType
  36. );
  37. property.SetValue(classObject, propertyValue, null);
  38. }
  39. }
  40. }
  41. }
  42. dataList.Add(classObject);
  43. }
  44. return dataList;
  45. }
  46. catch
  47. {
  48. return new List<T>();
  49. }
  50. }
  51. }
  52. }