锐腾搅拌上料功能
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.

65 lines
2.4 KiB

5 months ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace ICSSoft.Frame.Common
  6. {
  7. using System.Data;
  8. using System.Reflection;
  9. /// <summary>
  10. /// 将DataTable数据源转换成实体类
  11. /// </summary>
  12. /// <typeparam name="T">实体</typeparam>
  13. public static class ToModel<T> where T : new()
  14. {
  15. /// <summary>
  16. /// 将DataTable数据源转换成实体类
  17. /// </summary>
  18. public static List<T> ConvertToModel(DataTable dt)
  19. {
  20. List<T> ts = new List<T>();
  21. foreach (DataRow dr in dt.Rows)
  22. {
  23. T t = new T();
  24. PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
  25. foreach (PropertyInfo pi in propertys)
  26. {
  27. if (dt.Columns.Contains(pi.Name))
  28. {
  29. if (!pi.CanWrite) continue;
  30. var value = dr[pi.Name];
  31. if (value != DBNull.Value)
  32. {
  33. switch (pi.PropertyType.FullName)
  34. {
  35. case "System.Decimal":
  36. pi.SetValue(t, decimal.Parse(value.ToString()), null);
  37. break;
  38. case "System.String":
  39. pi.SetValue(t, value.ToString(), null);
  40. break;
  41. case "System.Int32":
  42. pi.SetValue(t, int.Parse(value.ToString()), null);
  43. break;
  44. case "System.Guid":
  45. pi.SetValue(t, new System.Guid(value.ToString()), null);
  46. break;
  47. case "System.Double":
  48. pi.SetValue(t, Convert.ToDouble(value ?? 0), null);
  49. break;
  50. default:
  51. pi.SetValue(t, value, null);
  52. break;
  53. }
  54. }
  55. }
  56. }
  57. ts.Add(t);
  58. }
  59. return ts;
  60. }
  61. }
  62. }