L.q*_*ter 5 api pagination entity-framework .net-core
我一直在寻找一种在 Dotnet Core 1.1 中使用实体框架进行通用分页的方法。
但这不是通用的,不允许我重用代码。
如果有人正在研究这个问题,其中包括我使用的答案,我认为分享会很好。
它在模型上使用自定义属性,并返回分页模型。
编辑:
由于 orderBy 未正确转换为 L2E,因此下面的答案不正确。所有记录都将在内存中检索并排序,这会导致性能不佳。查看评论以获取更多信息和可能的解决方案。
原文:
我的解决方案:
模型.cs:
public class User
{
// Sorting is not allowed on Id
public string Id { get; set; }
[Sortable(OrderBy = "FirstName")]
public string FirstName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
可排序属性.cs:
public class SortableAttribute : Attribute
{
public string OrderBy { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
分页服务.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;
}
}
Run Code Online (Sandbox Code Playgroud)
分页.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; }
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这对将来的人有帮助!
| 归档时间: |
|
| 查看次数: |
7790 次 |
| 最近记录: |