AdaptExtension.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. using Mapster;
  2. using System.Reflection;
  3. namespace Photo.Core.Extensions
  4. {
  5. /// <summary>
  6. /// 映射器扩展方法
  7. /// </summary>
  8. public static class AdaptExtension
  9. {
  10. /// <summary>
  11. /// 映射器扩展方法-将input中带有AdaptMemberAttribute标识的字段自动转换赋值至实体对象中
  12. /// </summary>
  13. /// <typeparam name="T_input"></typeparam>
  14. /// <typeparam name="T_entity"></typeparam>
  15. /// <param name="input"></param>
  16. /// <param name="entity"></param>
  17. public static void AdaptTo<T_input, T_entity>(this T_input input, ref T_entity entity)
  18. {
  19. foreach (PropertyInfo p in typeof(T_input).GetProperties())//遍历入参,判断入参中是否包含AdaptMemberAttribute头缀,包含即赋值
  20. {
  21. var adaptMemberAttribute = System.Attribute.GetCustomAttribute(p, typeof(AdaptMemberAttribute)) as AdaptMemberAttribute;
  22. if (adaptMemberAttribute != null)//判断是否具有AdaptMemberAttribute
  23. {
  24. //实体类所对应的属性
  25. var entityValue = typeof(T_entity).GetProperty(p.Name).GetValue(entity);
  26. var inputValue = p.GetValue(input);
  27. if (inputValue != entityValue)
  28. {
  29. typeof(T_entity).GetProperty(p.Name).SetValue(entity, inputValue);
  30. }
  31. }
  32. }
  33. }
  34. }
  35. }