DotNetCore实体框架|通用分页

时间:2017-08-15 11:07:45

标签: entity-framework api pagination .net-core

我一直在寻找一种在Dotnet Core 1.1中使用Entity Framework进行泛型分页的方法。

我在MSDN上找到了这个指南:https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

但这不是通用的,不允许我重用代码。

如果有人对此进行调查,我会使用的答案包括在内,我认为分享会很好。

它在模型上使用自定义属性,并返回分页模型。

1 个答案:

答案 0 :(得分:1)

编辑:

由于订单未正确转换为L2E,以下答案不正确。将检索所有记录并在内存中进行排序,这会导致性能下降。查看评论以获取更多信息和有争议的解决方案。

一部开拓创新:

我的解决方案:

Model.cs:

public class User
{

    // Sorting is not allowed on Id
    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);
        }
    }

我希望这有助于将来的某个人!