此文提供一个初步的封装思路,简化代码编写。
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); }
标签:封装,pageSize,int,IQueryable,EFore,ResultSet,source,链式,public From: https://www.cnblogs.com/NewBigLiang/p/17098922.html