EntityAttributeHelper.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.ComponentModel.DataAnnotations.Schema;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace Common
  6. {
  7. public sealed class EntityAttributeHelper
  8. {
  9. /// <summary>
  10. /// 获取实体对象表名
  11. /// </summary>
  12. /// <returns></returns>
  13. public static string GetEntityTable<T>()
  14. {
  15. Type objTye = typeof(T);
  16. string entityName = "";
  17. var tableAttribute = objTye.GetCustomAttributes(true).OfType<TableAttribute>();
  18. var descriptionAttributes = tableAttribute as TableAttribute[] ?? tableAttribute.ToArray();
  19. entityName = descriptionAttributes.Any() ? descriptionAttributes.ToList()[0].Name : objTye.Name;
  20. return entityName;
  21. }
  22. /// <summary>
  23. /// 获取实体对象Key
  24. /// </summary>
  25. /// <returns></returns>
  26. public static string GetEntityKey<T>()
  27. {
  28. Type objTye = typeof(T);
  29. string entityName = "";
  30. var tableAttribute = objTye.GetCustomAttributes(true).OfType<Key>();
  31. var descriptionAttributes = tableAttribute as Key[] ?? tableAttribute.ToArray();
  32. entityName = descriptionAttributes.Any() ? descriptionAttributes.ToList()[0].Name : objTye.Name;
  33. return entityName;
  34. }
  35. /// <summary>
  36. /// 获取ApiAction值
  37. /// </summary>
  38. /// <returns></returns>
  39. public static string GetMark<T>()
  40. {
  41. Type objTye = typeof(T);
  42. string entityName = "";
  43. var tableAttribute = objTye.GetCustomAttributes(true).OfType<MarkAttribute>();
  44. var descriptionAttributes = tableAttribute as MarkAttribute[] ?? tableAttribute.ToArray();
  45. entityName = descriptionAttributes.Any() ? descriptionAttributes.ToList()[0].Name : objTye.Name;
  46. return entityName;
  47. }
  48. /// <summary>
  49. /// 获取访问元素
  50. /// </summary>
  51. /// <param name="type"></param>
  52. /// <returns></returns>
  53. public static PropertyInfo[] GetProperties(Type type)
  54. {
  55. return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  56. }
  57. /// <summary>
  58. /// 获取实体对象表名
  59. /// </summary>
  60. /// <returns></returns>
  61. public static string GetCalssTable<T>()
  62. {
  63. Type objTye = typeof(T);
  64. if (objTye.Name.Contains("List"))
  65. {
  66. objTye = objTye.GenericTypeArguments[0];
  67. }
  68. string entityName = "";
  69. try
  70. {
  71. var tableAttribute = objTye.GetCustomAttributes(true).OfType<TableAttribute>();
  72. var descriptionAttributes = tableAttribute as TableAttribute[] ?? tableAttribute.ToArray();
  73. entityName = descriptionAttributes.Any() ? descriptionAttributes.ToList()[0].Name : objTye.Name;
  74. }
  75. catch (Exception e)
  76. {
  77. }
  78. return entityName+"_";
  79. }
  80. }
  81. }