EFore 分页查询 链式封装

此文提供一个初步的封装思路,简化代码编写。

1. 先封装一个 ResultSet 存放查询结果:

复制代码
    public class ResultSet<T>
    {
        /// <summary>
        /// 总记录数
        /// </summary>
        public int Total { get; set; }

        public List<T> Value { get; set; }
    }
复制代码

2. 封装三个扩展方法: WhereIf,  IfNotnull,PageQuery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static class ExtendMethods
{
    public static IQueryable<T> WhereIf<T>(this IQueryable<T> source,bool condition, Expression<Func<T, bool>> predicate)
    {
        if (condition)
        {
            source = source.Where(predicate);
        }
        return source;
    }
    public static IQueryable<T> IfNotNull<T>(this IQueryable<T> source, string condition, Expression<Func<T, bool>> predicate)
    {
        if (!string.IsNullOrEmpty(condition))
        {
            source = source.Where(predicate);
        }
        return source;
    }
    public static ResultSet<T> PageQuery<T>(this IQueryable<T> source, int pageSize,int page)
    {
        var count  =source.Count();
        var data  = source.Skip((page - 1) * pageSize).Take(pageSize).ToList();
        return new ResultSet<T>()
        {
            Total = count,
            Value = data
        };
    }
}

  3. 使用示例:

1
2
3
4
5
6
7
public ResultSet<Users> GetData(int pageSize, int page, string userName, string keyWords = "")
      {
          return _context.Set<Users>
              .IfNotNull(userName, u => u.UserName == userName)
              .WhereIf(!string.IsNullOrWhiteSpace(keyWords), u => u.Name.Contains(keyWords))
              .PageQuery(pageSize, page);
      }

  

 

posted @   BigLiang  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示