技术控

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

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

[复制链接]
如烟绕梁 发表于 2016-10-11 05:21:14
51 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
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!
友荐云推荐




上一篇:When DVRs Attack: A Post IoT Attack Analysis
下一篇:Building Instagram Stories using React Native
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表