EntityTool.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections;
  6. using System.Data;
  7. namespace Core.StlMes.Client.ZGMil.Common
  8. {
  9. class EntityTool
  10. {
  11. /// <summary>
  12. /// 返回实体类属性对应的数据库字段名
  13. /// </summary>
  14. /// <typeparam name="T"></typeparam>
  15. /// <param name="t"></param>
  16. /// <returns></returns>
  17. public static ArrayList getProperties<T>(T t)
  18. {
  19. ArrayList EntilyProName = new ArrayList();
  20. if (t == null)
  21. {
  22. return EntilyProName;
  23. }
  24. System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
  25. if (properties.Length <= 0)
  26. {
  27. return EntilyProName;
  28. }
  29. foreach (System.Reflection.PropertyInfo item in properties)
  30. {
  31. string name = item.Name;
  32. EntilyProName.Add(name);
  33. }
  34. return EntilyProName;
  35. }
  36. /// <summary>
  37. /// 数据库字段名转换成实体类属性名
  38. /// </summary>
  39. /// <param name="strName"></param>
  40. /// <returns></returns>
  41. public static string SQLColumnNameToEntityName(string strName)
  42. {
  43. string[] sArray = strName.Split(new char[1] { '_' });
  44. string Rstring = "";
  45. foreach (string str in sArray)
  46. {
  47. string temp = "";
  48. //temp = str.ToLower();
  49. temp = str.Substring(0, 1).ToUpper() + str.Substring(1).ToLower(); ;
  50. Rstring += temp;
  51. }
  52. return Rstring;
  53. }
  54. public static Object setObjectByDataTable(Object obj, DataTable dt)
  55. {
  56. System.Reflection.PropertyInfo[] properties = obj.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
  57. foreach (System.Reflection.PropertyInfo item in properties)
  58. {
  59. string name = item.Name;
  60. // string value = item.GetValue(obj, null).ToString();
  61. foreach (DataRow dr in dt.Rows)
  62. {
  63. if (SQLColumnNameToEntityName(dr[0].ToString()).Equals(name))
  64. {
  65. item.SetValue(obj, dr[1].ToString(), null);
  66. }
  67. }
  68. }
  69. return obj;
  70. }
  71. }
  72. }