EntityAttributeHelper.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using FCS.Models;
  8. namespace FCS.Common
  9. {
  10. /// <summary>
  11. /// 获取实体类Attribute自定义属性
  12. /// </summary>
  13. public sealed class EntityAttributeHelper
  14. {
  15. /// <summary>
  16. /// 获取实体对象表名
  17. /// </summary>
  18. /// <returns></returns>
  19. public static string GetEntityTable<T>()
  20. {
  21. Type objTye = typeof(T);
  22. string entityName = "";
  23. var tableAttribute = objTye.GetCustomAttributes(true).OfType<TableAttribute>();
  24. var descriptionAttributes = tableAttribute as TableAttribute[] ?? tableAttribute.ToArray();
  25. entityName = descriptionAttributes.Any() ? descriptionAttributes.ToList()[0].Name : objTye.Name;
  26. return entityName;
  27. }
  28. /// <summary>
  29. /// 获取实体类 字段中文名称
  30. /// </summary>
  31. /// <param name="pi">字段属性信息</param>
  32. /// <returns></returns>
  33. public static string GetFieldText(PropertyInfo pi)
  34. {
  35. string txt = "";
  36. var descAttrs = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true);
  37. if (descAttrs.Any())
  38. {
  39. DisplayNameAttribute descAttr = descAttrs[0] as DisplayNameAttribute;
  40. if (descAttr != null) txt = descAttr.DisplayName;
  41. }
  42. else
  43. {
  44. txt = pi.Name;
  45. }
  46. return txt;
  47. }
  48. /// <summary>
  49. /// 获取实体类中文名称
  50. /// </summary>
  51. /// <returns></returns>
  52. public static string GetClassName<T>()
  53. {
  54. Type objTye = typeof(T);
  55. string entityName = "";
  56. var busingessNames = objTye.GetCustomAttributes(true).OfType<DisplayNameAttribute>();
  57. var descriptionAttributes = busingessNames as DisplayNameAttribute[] ?? busingessNames.ToArray();
  58. if (descriptionAttributes.Any())
  59. {
  60. entityName = descriptionAttributes.ToList()[0].DisplayName;
  61. }
  62. else
  63. {
  64. entityName = objTye.Name;
  65. }
  66. return entityName;
  67. }
  68. /// <summary>
  69. /// 获取访问元素
  70. /// </summary>
  71. /// <param name="type"></param>
  72. /// <returns></returns>
  73. public static PropertyInfo[] GetProperties(Type type)
  74. {
  75. return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  76. }
  77. }
  78. }