BaseServices.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Reflection;
  7. using SCC.Common;
  8. namespace SCC.Services
  9. {
  10. /// <summary>
  11. /// 基础服务
  12. /// </summary>
  13. public class BaseServices
  14. {
  15. /// <summary>
  16. /// 装箱单个数据对象
  17. /// </summary>
  18. /// <typeparam name="T">装箱对象</typeparam>
  19. /// <param name="dr">装箱数据行</param>
  20. /// <returns></returns>
  21. protected T LoadData<T>(DataRow dr)
  22. {
  23. if (dr == null) return default(T);
  24. var t = typeof(T);
  25. var obj = Activator.CreateInstance(t);
  26. var properts = t.GetProperties();
  27. foreach (var pi in properts)
  28. {
  29. if (!dr.Table.Columns.Contains(pi.Name)) continue;
  30. pi.SetValue(obj, CommonHelper.ChangeType(dr[pi.Name], pi.PropertyType), null);
  31. }
  32. return (T)obj;
  33. }
  34. /// <summary>
  35. /// 装箱列表数据对象
  36. /// </summary>
  37. /// <typeparam name="T">装箱对象</typeparam>
  38. /// <param name="dt">装箱数据来源表格</param>
  39. /// <returns></returns>
  40. protected List<T> LoadDataList<T>(DataTable dt)
  41. {
  42. List<T> result = new List<T>();
  43. var t = typeof(T);
  44. var properts = t.GetProperties();
  45. object obj;
  46. foreach (DataRow dr in dt.Rows)
  47. {
  48. obj = Activator.CreateInstance(t);
  49. foreach (var pi in properts)
  50. {
  51. if (!dt.Columns.Contains(pi.Name)) continue;
  52. pi.SetValue(obj, CommonHelper.ChangeType(dr[pi.Name], pi.PropertyType), null);
  53. }
  54. result.Add((T)obj);
  55. }
  56. return result;
  57. }
  58. }
  59. }