RepositoryExtension.cs 2.1 KB

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