EFore 分页查询 链式封装

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

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

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

        public List<T> Value { get; set; }
    }

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

    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. 使用示例:

  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 @ 2023-02-07 16:24  BigLiang  阅读(20)  评论(0编辑  收藏  举报