筛选和分页在.NET Core 2.1 EF中不起作用

时间:2018-07-31 16:08:57

标签: c# asp.net-core entity-framework-core

我尝试将过滤器和分页应用于我的GET查询。当filter和pagination不为null并且代码到达IF内部时发生的事件,查询始终返回所有类别。有什么问题吗?

public async Task<List<Category>> GetListAsync(CategoryListFilter filter = null, Paging paging = null)
{
    var categories = _context.Categories
        .Include(category => category.Image)
        .Include(category => category.Parent)
        .Include(category => category.CategoryProperties)
            .ThenInclude(property => property.Property)
                .ThenInclude(property => property.ValueType)
                    .ThenInclude(valueType => valueType.InputType);

    if (filter != null && !String.IsNullOrEmpty(filter.SearchText))
    {
        categories
            .Where(category => category.Title.Contains(filter.SearchText));
    }

    if(paging != null)
    {
        categories
            .Skip(paging.Offset)
            .Take(paging.Limit);
    }

    return await categories.ToListAsync();
}

1 个答案:

答案 0 :(得分:2)

你肯定想念

categories = categories
            .Skip(paging.Offset)
            .Take(paging.Limit);

没有它,您将两者都调用,但丢弃结果。

Where子句也是如此。

(请注意,这可能需要为categories提供一个显式类型,以便分配的左侧和右侧都属于IQueryable<Category>