c# - 使用 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);
}
还是我需要在启动服务中设置任何东西才能工作?
谢谢蒂姆
解决方案
您不需要使用行号,一旦记录排序,您可以使用 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);
}
推荐阅读
- r - 创建 Padovan 序列的函数
- html - 只需使用标签并希望在移动平台中对其进行自定义
- spring-boot - 在springboot2.0中使用ehcache时'sync = true'是否有效
- sql - PostgreSQL 中的 percentile_cont 的奇怪结果是多年来每个 mmdd 的 count(*)
- c# - 将 [数据类型] nvarchar 转换为整数时出错
- c++ - Ratio<,> 是常数,但如果我想接受不同的比率作为参数怎么办?
- scheme - 方案 - 字符串附加两个字符串列表
- java - Java 错误:“org.apache.camel.FailedToCreateRouteException:无法创建路由 route1”
- adobe - 如何绕过机器人检查而不旋转我的 IP?
- c# - 为类的实例创建方法