AzureCosmosUtil.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Text;
  5. using TEAMModelOS.SDK.Context.Attributes.Azure;
  6. using TEAMModelOS.SDK.Context.Exception;
  7. namespace TEAMModelOS.SDK.DI.AzureCosmos.Inner
  8. {
  9. public static class AzureCosmosUtil
  10. {
  11. public static string GetPartitionKey<T>()
  12. {
  13. Type type = typeof(T);
  14. return GetPartitionKey(type);
  15. }
  16. public static string GetPartitionKey(Type type)
  17. {
  18. PropertyInfo[] properties = type.GetProperties();
  19. List<PropertyInfo> attrProperties = new List<PropertyInfo>();
  20. foreach (PropertyInfo property in properties)
  21. {
  22. if (property.Name.Equals("PartitionKey"))
  23. {
  24. attrProperties.Add(property);
  25. break;
  26. }
  27. object[] attributes = property.GetCustomAttributes(true);
  28. foreach (object attribute in attributes) //2.通过映射,找到成员属性上关联的特性类实例,
  29. {
  30. if (attribute is PartitionKeyAttribute)
  31. {
  32. attrProperties.Add(property);
  33. }
  34. }
  35. }
  36. if (attrProperties.Count <= 0)
  37. {
  38. throw new BizException(type.Name + " has no PartitionKey !");
  39. }
  40. else
  41. {
  42. if (attrProperties.Count == 1)
  43. {
  44. return attrProperties[0].Name;
  45. }
  46. else { throw new BizException(type.Name + " PartitionKey can only be single!"); }
  47. }
  48. }
  49. }
  50. }