请选择 进入手机版 | 继续访问电脑版

技术控

    今日:35| 主题:61447
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Entity Framework Pitfalls: Skip/Take Position Matters

[复制链接]
如烟绕梁 发表于 2016-10-11 05:21:14
67 0
In LINQ, you normally do paging through the    Skipand    Takeoperators. These are the LINQ counterparts to whatever the relational database uses for pagination –    ROW_NUMBER(),    LIMIT…OFFSET,    TOP,    ROWNUM, etc.  
  There are some gotchas to it:
  
       
  •       When you do paging, Entity Framework demands that you add ordering to your query. This makes sense as without an explicit        ORDER BYclause, search results may come in an unexpected order;      
       
  •               Skipand        Takeyield different results if added to different places in the LINQ expression.      
      
  Consider these two LINQ queries:
  1. ctx    .MyEntities    .Where(x => x.Name == "")    .OrderBy(x => x.Id)    .Skip(10)    .Take(5)    .ToList();
复制代码
And:
  1. ctx    .MyEntities    .OrderBy(x => x.Id)    .Skip(10)    .Take(5)    .Where(x => x.Name == "")    .ToList();
复制代码
The first one will produce this SQL:
  1. SELECT TOP (5)    [Filter1].[Id] AS [Id],    [Filter1].[Name] AS [Name],    [Filter1].[Date] AS [Date]    FROM ( SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], [Extent1].[Date] AS [Date], row_number() OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number]        FROM [dbo].[MyEntities] AS [Extent1]        WHERE N'' = [Extent1].[Name]    )  AS [Filter1]    WHERE [Filter1].[row_number] > 10    ORDER BY [Filter1].[Id] ASC
复制代码
Whereas the second will produce this one:
  1. SELECT    [Limit1].[Id] AS [Id],    [Limit1].[Name] AS [Name],    [Limit1].[Date] AS [Date]    FROM ( SELECT TOP (5) [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], [Extent1].[Date] AS [Date]        FROM ( SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], [Extent1].[Date] AS [Date], row_number() OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number]            FROM [dbo].[MyEntities] AS [Extent1]        )  AS [Extent1]        WHERE [Extent1].[row_number] > 10        ORDER BY [Extent1].[Id] ASC    )  AS [Limit1]    WHERE N'' = [Limit1].[Name]    ORDER BY [Limit1].[Id] ASC
复制代码
Basically, the    TOP(5)expression is placed in the wrong place. So, in LINQ, it’s not just the    presenceof a    Skipand    Takeoperator, it’s where you place it that matters!
我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表