首页 > 解决方案 > 使用 Entity Framework Core 和 C# 根据行号加载更多记录

问题描述

我有一个购物网站;当我点击“加载更多”时,我想加载另一组记录,可能还有 10 个。我正在尝试使用行号来获取记录。我看到了一个使用存储过程的示例,但我想使用 Entity Framework Core。

这是我的代码 - 我收到此错误:

Processing of the LINQ expression 'DbSet<Product>
.OrderBy(t => t.ID)
.Select((t, i) => new { 
    row = i, 
    ID = t.ID, 
    Category = t.Category, 
    Description = t.Description, 
    Name = t.Name, 
    PicPathLeft = t.PicPathLeft, 
    PicPathMain = t.PicPathMain, 
    PicPathRight = t.PicPathRight, 
    Price = t.Price, 
    Size = t.Size
 })' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.

这是我的代码:

public JsonResult GetMoreProducts(int count)
{
   var start = ((page - 1) * pageSize) + 1;
   var end = page * pageSize;

   var query2 = db.Product.OrderBy(t => t.ID)
                    .Select((t, i) => new
                    {
                        row = i,
                        t.ID,
                        t.Category,
                        t.Description,
                        t.Name,
                        t.PicPathLeft,
                        t.PicPathMain,
                        t.PicPathRight,
                        t.Price,
                        t.Size
                    }).ToList().Where(x => x.row <= end && x.row >= start);

   var dataContainer2 = query2.Take(pageSize).ToList();
   return Json(dataContainer2);
 }

还是我需要在启动服务中设置任何东西才能工作?

谢谢蒂姆

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

解决方案


您不需要使用行号,一旦记录排序,您可以使用 Skip() 和 Take() 方法。在这种情况下,通过 (pageSize * pageNumber) 计算要跳过的记录数。我还建议在最后调用 ToList() 一次,这将执行查询并确保将最小的结果集加载到内存中。

    public JsonResult GetMoreProducts(int pageNumber, int pageSize)
    {
        var query2 = db.Product
            .OrderBy(t => t.ID)
            .Select(t => new
            {
                t.ID,
                t.Category,
                t.Description,
                t.Name,
                t.PicPathLeft,
                t.PicPathMain,
                t.PicPathRight,
                t.Price,
                t.Size
            });

        var results = query2
            .Skip(pageSize * pageNumber)
            .Take(pageSize)
            .ToList();

        return Json(results);
    }

推荐阅读