[英]Entity Framework and IEnumerable
I have written a paging function that I had hoped would do an EF safe paging. 我编写了一个分页功能,希望该功能可以进行EF安全分页。 It seems though that this functions executes the EF query BEFORE paging, where as what I would like it to do is defer the paging to the database. 尽管该函数似乎在分页之前执行EF查询,但我想做的是将分页推迟到数据库。 I thought IEnumerable would be safe but it appears it is not. 我认为IEnumerable将是安全的,但事实并非如此。 What is happening here? 这是怎么回事
private IEnumerable<T> PageList<T>(IEnumerable<T> list, PaginationOptions options)
{
return list.Skip((options.Page - 1) * options.ResultsPerPage).Take(options.ResultsPerPage);
}
If I test this as a function vs the actual function called one generates SQL that contains the paging information and the other (the function) doesnt. 如果我将其作为一个函数与实际函数进行测试,则一个函数会生成包含分页信息的SQL,而另一个(函数)则不会。
var pagedStuff = this.PageList(activities, options); // doesnt create correct query
var pagedStuff = activities.Skip((options.Page - 1) * options.ResultsPerPage).Take(options.ResultsPerPage);
Ps I use IEnumerable as sometimes this function is used for normal Lists. ps我使用IEnumerable,因为有时此功能用于普通列表。
I use
IEnumerable
as sometimes this function is used for normalList
s 我使用IEnumerable
因为有时此函数用于普通List
。
You may want to consider making an IQueryable
overload as well: 您可能还需要考虑进行IQueryable
重载:
private IQueryable<T> PageList<T>(IQueryable<T> list, PaginationOptions options)
{
return list.Skip((options.Page - 1) * options.ResultsPerPage).Take(options.ResultsPerPage);
}
The problem is that since the input is an IEnumerable
, the query is being executed before the paging is applied, so you get all records back and the paging is done in Linq-to-Objects. 问题在于,由于输入是IEnumerable
,因此在应用分页之前正在执行查询,因此您可以取回所有记录,并且分页是在Linq-to-Objects中完成的。
Using IQueryable
delays the execution of the query until after the paging is applied. 使用IQueryable
延迟查询的执行施加寻呼后直到。
You're invoking IEnumerable.Skip/Take
instead of IQueryable.Skip/Take
. 您正在调用IEnumerable.Skip/Take
而不是IQueryable.Skip/Take
。
Try to use the AsQueryable
method: 尝试使用AsQueryable
方法:
return list.AsQueryable()
.Skip((options.Page - 1) * options.ResultsPerPage)
.Take(options.ResultsPerPage);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.