当获取的记录越来越多时,为什么“跳过”和“取走”会花费更长的时间?

时间:2019-02-22 06:03:53

标签: c# entity-framework entity-framework-6

表中的-\A\B \\A\B\ \\A\B\ 个以上。我正在使用50,000 records

我已经使用该代码一次获取200条记录。下面的代码似乎可以正常工作直到1000条记录,但此后它开始需要更长的时间。

代码

Microsoft SQL Server 2016 (RTM-GDR)

生成的SQL代码

int skip = 0; //Initially and gets increased by 200 for each calls (0, 200, 400, so on)
int take = 200; //Initially and remains same since only 200 records needed at a time.

var recordList = context.Records.OrderBy(x => x.IncentiveOUID)
                                .Skip(skip)
                                .Take(take)
                                .ToList();

如果需要解释以上内容,随时准备提供更多信息。

1 个答案:

答案 0 :(得分:1)

SQL没有有效的方法来Skip:它必须读取所有前面的行。每次获取一页记录时,您都在对索引执行扫描,而每一页都会扫描越来越多的索引。

考虑分页获取而不是分页结果。像这样:

IEnumerable<Record> GetNext(int fromId = 0, int take = 50) => context.Records
    .Where(x => x.Id > fromId)
    .OrderBy(x => x.Id)
    .Take(take)
    .ToList();

索引为Id的索引将转化为最大效率的索引查找。

相关问题