【转】IEnumerable的谨慎使用和IQueryable 的延迟执行
时间:2010-12-16 来源:チャチャの楽園
代码:
public PageList(IEnumerable<T> source, int index, int pageSize,int totalCount)
{
this.AddRange(source.Skip(index*pageSize).Take(pageSize));
this.TotalCount = source.Count();
this.PageSize=pageSize;
this.PageIndex=index;
this.TotalPageCount = (int)Math.Ceiling(TotalCount / (double)PageSize);
}
用SQL Server profiler 工具查看一下SQL 语句时果然IEnumerable<T>把所有的数据加载下来了再对其进行选择其中的数据,sql代码如下:
[Extent1].[FID] AS [FID],
[Extent1].[BookName] AS [BookName],
[Extent1].[Author] AS [Author]
FROM ( SELECT [Extent1].[FID] AS [FID], [Extent1].[BookName] AS [BookName], [Extent1].[Author] AS [Author], row_number() OVER (ORDER BY [Extent1].[FID] ASC) AS
[row_number]
FROM [dbo].[Book] AS [Extent1]
) AS [Extent1]
WHERE [Extent1].[row_number] > 0
ORDER BY [Extent1].[FID] ASC
由些可见IEnumerable生成的SQL语句是查询所有的数据,而不是生成查询指定记录的SQL语句。在上面PageList 的构造函数中 使用IEnumerable<T> source 参数,当我把IEnumerable<T> 把换成IQueryable<T>后再执行时发现速度明显提高了,再有SQL Server profiler 工具查看一下SQL代码:
[Extent1].[FID] AS [FID],
[Extent1].[BookName] AS [BookName],
[Extent1].[Author] AS [Author]
FROM ( SELECT [Extent1].[FID] AS [FID], [Extent1].[BookName] AS [BookName], [Extent1].[Author] AS [Author], row_number() OVER (ORDER BY [Extent1].[FID] ASC) AS
[row_number]
FROM [dbo].[Book] AS [Extent1]
) AS [Extent1]
WHERE [Extent1].[row_number] > 0
ORDER BY [Extent1].[FID] ASC
显然,这个才是我们真正需要的(因为我设置的是每页10条数据)--只查询我们指定数据。
思索结果:
相关阅读 更多 +