编辑:
由于orderBy无法正确转换为L2E,下面的答案是不正确的。所有记录将在内存中检索和排序,导致性能不佳。请查看评论以获取更多信息和可能的解决方案。
原始内容:
我的解决方案:
Model.cs:
public class User
{
public string Id { get; set; }
[Sortable(OrderBy = "FirstName")]
public string FirstName { get; set; }
}
SortableAttribute.cs:
public class SortableAttribute : Attribute
{
public string OrderBy { get; set; }
}
PaginationService.cs:
public static class PaginationService
{
public static async Task<Pagination<T>> GetPagination<T>(IQueryable<T> query, int page, string orderBy, bool orderByDesc, int pageSize) where T : class
{
Pagination<T> pagination = new Pagination<T>
{
TotalItems = query.Count(),
PageSize = pageSize,
CurrentPage = page,
OrderBy = orderBy,
OrderByDesc = orderByDesc
};
int skip = (page - 1) * pageSize;
var props = typeof(T).GetProperties();
var orderByProperty = props.FirstOrDefault(n => n.GetCustomAttribute<SortableAttribute>()?.OrderBy == orderBy);
if (orderByProperty == null)
{
throw new Exception($"Field: '{orderBy}' is not sortable");
}
if (orderByDesc)
{
pagination.Result = await query
.OrderByDescending(x => orderByProperty.GetValue(x))
.Skip(skip)
.Take(pageSize)
.ToListAsync();
return pagination;
}
pagination.Result = await query
.OrderBy(x => orderByProperty.GetValue(x))
.Skip(skip)
.Take(pageSize)
.ToListAsync();
return pagination;
}
}
Pagination.cs(模型):
public class Pagination<T>
{
public int CurrentPage { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public int TotalItems { get; set; }
public string OrderBy { get; set; }
public bool OrderByDesc { get; set; }
public List<T> Result { get; set; }
}
UserController.cs(控制器内部),上下文是EntityFramework上下文:
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery] string orderBy, [FromQuery] bool orderByDesc, [FromQuery] int page, [FromQuery] int size)
{
var query = _context.User.AsQueryable();
try
{
var list = await PaginationService.GetPagination(query, page, orderBy, orderByDesc, size);
return new JsonResult(list);
}
catch (Exception e)
{
return new BadRequestObjectResult(e.Message);
}
}
我希望这能帮助未来某个时候需要的人!
string orderBy
,直接传递表达式 (Expression<Func<T, object>> orderBy
) 并执行OrderBy(orderBy)
。 - DavidG