RepositoryExtension.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using Furion;
  2. using Furion.FriendlyException;
  3. using Mapster;
  4. using MapsterMapper;
  5. using SqlSugar;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Linq.Expressions;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace Admin.NET.Core.Extension
  13. {
  14. public static class RepositoryExtension
  15. {
  16. /// <summary>
  17. /// 实体假删除 _rep.Context.Updateable(entity).FakeDelete().ExecuteCommandAsync();
  18. /// </summary>
  19. /// <typeparam name="T"></typeparam>
  20. /// <param name="updateable"></param>
  21. /// <returns></returns>
  22. public static IUpdateable<T> FakeDelete<T>(this IUpdateable<T> updateable) where T : EntityBase, new()
  23. {
  24. return updateable.ReSetValue(x => { x.IsDelete = true; })
  25. .IgnoreColumns(ignoreAllNullColumns: true)
  26. .EnableDiffLogEvent() // 记录差异日志
  27. .UpdateColumns(x => new { x.IsDelete, x.UpdateTime, x.UpdateUserId }); // 允许更新的字段-AOP拦截自动设置UpdateTime、UpdateUserId
  28. }
  29. /// <summary>
  30. /// 排序方式(默认降序)
  31. /// </summary>
  32. /// <param name="queryable"></param>
  33. /// <param name="pageInput"> </param>
  34. /// <param name="defualtSortField"> 默认排序字段 </param>
  35. /// <param name="descSort"> 是否降序 </param>
  36. /// <returns> </returns>
  37. public static ISugarQueryable<T> OrderBuilder<T>(this ISugarQueryable<T> queryable, BasePageInput pageInput, string defualtSortField = "Id", bool descSort = true)
  38. {
  39. var orderStr = "";
  40. // 约定默认每张表都有Id排序
  41. if (!string.IsNullOrWhiteSpace(defualtSortField))
  42. {
  43. orderStr = descSort ? defualtSortField + " Desc" : defualtSortField + " Asc";
  44. }
  45. TypeAdapterConfig config = new();
  46. config.ForType<T, BasePageInput>().IgnoreNullValues(true);
  47. Mapper mapper = new(config); // 务必将mapper设为单实例
  48. var nowPagerInput = mapper.Map<BasePageInput>(pageInput);
  49. // 排序是否可用-排序字段和排序顺序都为非空才启用排序
  50. if (!string.IsNullOrEmpty(nowPagerInput.Field) && !string.IsNullOrEmpty(nowPagerInput.Order))
  51. {
  52. orderStr = $"{nowPagerInput.Field} {(nowPagerInput.Order == nowPagerInput.DescStr ? "Desc" : "Asc")}";
  53. }
  54. return queryable.OrderByIF(!string.IsNullOrWhiteSpace(orderStr), orderStr);
  55. }
  56. }
  57. }