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

技术控

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

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

[复制链接]
如烟绕梁 发表于 2016-10-11 05:21:14
65 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
*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读


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

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

返回顶部 返回列表