ModelConvertHelper.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using System.Data;
  6. using System.Reflection;
  7. using System.Collections;
  8. namespace Common.Model
  9. {
  10. /// <summary>
  11. /// 实体转换辅助类
  12. /// </summary>
  13. public class ModelConvertHelper<T> where T : new()
  14. {
  15. public static IList<T> ConvertToModel(DataTable dt,bool IsDateTimeEmpty = false)
  16. {
  17. // 定义集合
  18. IList<T> ts = new List<T>();
  19. // 获得此模型的类型
  20. Type type = typeof(T);
  21. string tempName = "";
  22. foreach (DataRow dr in dt.Rows)
  23. {
  24. T t = new T();
  25. // 获得此模型的公共属性
  26. PropertyInfo[] propertys = t.GetType().GetProperties();
  27. foreach (PropertyInfo pi in propertys)
  28. {
  29. tempName = pi.Name; // 检查DataTable是否包含此列
  30. if (dt.Columns.Contains(tempName))
  31. {
  32. // 判断此属性是否有Setter
  33. if (!pi.CanWrite) continue;
  34. object value = dr[tempName];
  35. if (value != DBNull.Value)
  36. {
  37. //加一重if判断,如果属性值是int32类型的,就进行一次强制转换
  38. if (pi.GetMethod.ReturnParameter.ParameterType.Name == "Int32")
  39. {
  40. value = Convert.ToInt32(value);
  41. }
  42. pi.SetValue(t, value, null);
  43. }
  44. if (IsDateTimeEmpty)
  45. {
  46. if (pi.PropertyType.ToString() == "System.DateTime")
  47. {
  48. if (value.ToString() == DateTime.MinValue.ToString())
  49. {
  50. pi.SetValue(t, value, null);
  51. }
  52. }
  53. }
  54. }
  55. }
  56. ts.Add(t);
  57. }
  58. return ts;
  59. }
  60. /// <summary>
  61. /// list转datatable
  62. /// </summary>
  63. /// <typeparam name="T"></typeparam>
  64. /// <param name="collection"></param>
  65. /// <returns></returns>
  66. public DataTable ListToDt<T>(IEnumerable<T> collection)
  67. {
  68. var props = typeof(T).GetProperties();
  69. var dt = new DataTable();
  70. dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
  71. if (collection.Count() > 0)
  72. {
  73. for (int i = 0; i < collection.Count(); i++)
  74. {
  75. ArrayList tempList = new ArrayList();
  76. foreach (PropertyInfo pi in props)
  77. {
  78. object obj = pi.GetValue(collection.ElementAt(i), null);
  79. tempList.Add(obj);
  80. }
  81. object[] array = tempList.ToArray();
  82. dt.LoadDataRow(array, true);
  83. }
  84. }
  85. return dt;
  86. }
  87. }
  88. }