PropertyManage.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace DapperORMCore.Dapper
  7. {
  8. /// <summary>
  9. /// 操作属性管理
  10. /// </summary>
  11. public class PropertyManage
  12. {
  13. /// <summary>
  14. /// Key对应结果
  15. /// </summary>
  16. /// <param name="keys"></param>
  17. /// <param name="separator"></param>
  18. /// <returns></returns>
  19. public static string GetSqlPairs
  20. (IEnumerable<string> keys, string separator = ", ")
  21. {
  22. var pairs = keys.Select(key => string.Format("{0}=@{0}", key)).ToList();
  23. return string.Join(separator, pairs);
  24. }
  25. /// <summary>
  26. /// 设置Id
  27. /// </summary>
  28. /// <typeparam name="T"></typeparam>
  29. /// <param name="obj"></param>
  30. /// <param name="id"></param>
  31. /// <param name="propertyPairs"></param>
  32. public static void SetId<T>(T obj, int id, IDictionary<string, object> propertyPairs)
  33. {
  34. //对象属性
  35. if (propertyPairs.Count == 1)
  36. {
  37. var propertyName = propertyPairs.Keys.First();
  38. var propertyInfo = obj.GetType().GetProperty(propertyName);
  39. if (propertyInfo.PropertyType == typeof(int))
  40. {
  41. propertyInfo.SetValue(obj, id, null);
  42. }
  43. }
  44. }
  45. /// <summary>
  46. /// 检索具有名称和值的字典
  47. /// 与给定条件匹配的所有对象属性。
  48. /// </summary>
  49. public static PropertyContainer ParseProperties<T>(T obj)
  50. {
  51. var propertyContainer = new PropertyContainer();
  52. var typeName = typeof(T).Name;
  53. var validKeyNames = new[] { "Id",
  54. string.Format("{0}Id", typeName), string.Format("{0}_Id", typeName) };
  55. var properties = typeof(T).GetProperties();
  56. foreach (var property in properties)
  57. {
  58. // Skip reference types (but still include string!)
  59. if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
  60. continue;
  61. // Skip methods without a public setter
  62. if (property.GetSetMethod() == null)
  63. continue;
  64. // Skip methods specifically ignored
  65. if (property.IsDefined(typeof(DapperIgnore), false))
  66. continue;
  67. var name = property.Name;
  68. var value = typeof(T).GetProperty(property.Name).GetValue(obj, null);
  69. if (property.IsDefined(typeof(DapperKey), false) || validKeyNames.Contains(name))
  70. {
  71. propertyContainer.AddId(name, value);
  72. }
  73. else
  74. {
  75. propertyContainer.AddValue(name, value);
  76. }
  77. }
  78. return propertyContainer;
  79. }
  80. }
  81. }