public static IQueryable <T> SortQuery <T>(BasePagingRequest model, IQueryable <T> query, Boolean isSearchByCreatedAtDesc = false) where T : class { if (!query.HasElement()) { return(query); } if (model.SortNames.HasElement() && !model.SortNames.Any(s => s.IsNullOrEmpty()) && model.SortDirections.HasElement() && model.SortNames.Count == model.SortDirections.Count) { for (int i = 0; i < model.SortNames.Count; i++) { string direction = model.SortDirections[i].ToString(); if (i != 0) { direction = direction.Replace("Order", "Then"); } var exp = LinqHelper.GenerateMethodCall <T>(query, direction, model.SortNames[i]); query = query.Provider.CreateQuery <T>(exp); } } else { // if class default has not field createdAt, it not do any thing var propertyInfo = query.First().GetType().GetProperty("CreatedAt", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propertyInfo != null) { if (isSearchByCreatedAtDesc) { query = query.OrderByDescending(e => propertyInfo.GetValue(e, null)); } else { query = query.OrderBy(e => propertyInfo.GetValue(e, null)); } } } return(query); }
/// <summary> /// 实现对数据的分页查询 /// </summary> /// <param name="whereLambda">查询条件</param> /// <param name="total">总条数</param> /// <param name="pageIndex">当前第几页</param> /// <param name="pageSize">一页显示多少条数据</param> /// <param name="order">DESC/ASC</param> /// <param name="sort">排序字段</param> /// <returns></returns> public BasePagingResponse <TResult> LoadPaging <TResult>(Expression <Func <T, bool> > whereLambda, Expression <Func <T, TResult> > selector, BasePagingRequest request) where TResult : BaseItemResponse { var result = _repository.LoadPaging(whereLambda, selector, out int total, request.PageIndex, request.PageSize, request.Direction, request.SortField); var resultItems = result.ToList(); return(new BasePagingResponse <TResult> { Count = total, Total = total % request.PageSize == 0 ? total / request.PageSize : total / request.PageSize + 1, Items = resultItems }); }
/// <summary> /// 实现对数据的分页查询 /// </summary> /// <param name="whereLambda">查询条件</param> /// <param name="total">总条数</param> /// <param name="pageIndex">当前第几页</param> /// <param name="pageSize">一页显示多少条数据</param> /// <param name="order">DESC/ASC</param> /// <param name="sort">排序字段</param> /// <returns></returns> public async Task <TResult> GetListPagingAsync <TSelect, TResult>(Expression <Func <T, TSelect> > selector, Expression <Func <T, bool> > whereLambda, BasePagingRequest request) where TSelect : BaseItemResponse where TResult : BasePagingResponse <TSelect>, new() { var result = await _repository.GetListPagingAsync(whereLambda, selector, request.PageIndex, request.PageSize, request.Direction, request.SortField); return(new TResult { Count = result.Count, Total = result.Total, Items = result.Items }); }