EF Core 中的 OrderBy 对所有列进行排序

问题描述 投票:0回答:1

该标题包含产品型号的所有列。我要申请 仅过滤“标题”列。但我不知道为什么Controller中的OrderBy方法,对Product模型的所有属性应用过滤器。

 <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">
                        <a asp-action="Index" asp-route-sortOrder="@ViewData["TitleSortParam"]">Title</a>
                    </th>
                    <th scope="col">ISBN</th>
                    <th scope="col">List Price</th>
                    <th scope="col">Author</th>
                    <th scope="col">Category</th>
                    <th scope="col"></th>
                </tr>
            </thead>
public IActionResult Index([FromQuery] int? tableLength, string? sortOrder)
        {
            ViewData["TitleSortParam"] = String.IsNullOrEmpty(sortOrder) ? "title_desc" : "";

            IEnumerable<Product> objProductList =
                _unitOfWork.ProductRepo.GetAll
                (
                    null,
                    includeProperties: "Category",
                    takeEntities: tableLength
                );

            switch (sortOrder)
            {
                case "title_desc":
                    objProductList = objProductList.OrderByDescending(s => s.Title);
                    break;

            }



            return View(objProductList.ToList());
        }

这是 GetAll() 方法代码:

有关更多信息,如果您想在 Include() 中包含模型 ecc 的某些属性,这里我应用了添加 AsNoTracking 的可能性,以使用Where() 方法添加条件。

public IEnumerable<T> GetAll(
            Expression<Func<T, bool>>? filter = null,
            string? includeProperties = null,
            bool enableAsNoTracking = false,
            int? takeEntities = null
        )
        {

            IQueryable<T> query = _dbSet;

            if (enableAsNoTracking)
            {
                query = query.AsNoTracking();
            }

            if (filter != null)
            {
                query = query.Where(filter);
            }

            if (!string.IsNullOrEmpty(includeProperties))
            {
                foreach (
                    var property in includeProperties
                    .Split(
                        new char[] { ',' },
                        StringSplitOptions.RemoveEmptyEntries)
                    )
                {
                    query = query.Include(property);
                }
            }

            if (takeEntities != null && takeEntities > 0)
            {
                query = query.Take((int)takeEntities);
            }

            return query.ToList();
        }
asp.net-core sorting entity-framework-core sql-order-by filtering
1个回答
0
投票

就您而言,我认为您正在寻找 .Sort() 而不是 OrderByDescending

按降序排列=> 用于对元素集合进行排序 基于 specified key 或属性的降序排列。 它实际上并不过滤属性

© www.soinside.com 2019 - 2024. All rights reserved.