IQueryable失去了ORDER BY

时间:2015-07-20 15:18:05

标签: vb.net linq lambda sqlprofiler

任何人都可以解释为什么会这样吗?

Dim lReturn As IQueryable(Of Inventory) = context.Inventories.OrderBy(Function(o) o.SortOrder)

'' --- In the sql profiler, I can see Order by is added
'' Dim lst = lReturn.ToList 

If Not loggedInUser.IsAdmin Then
    lReturn = lReturn.Where(Function(x) x.AdminOnly = False)
    '' --- In the sql profiler, I can see Order by is added
    '' Dim lst = lReturn.ToList 

    lReturn = From f In lReturn
              Group Join a In context.AssignServices On f.ID Equals a.Id Into fas = Group
              From a In fas.Where(Function(x) x.AgentId = loggedInUser.CompanyId).DefaultIfEmpty()
              Where a.Assign = True OrElse f.isVisibleToAllAgents = True
              Select f
    '' --- In the sql profiler, I can see **Order by is not included**
    Dim lst = lReturn.ToList     ''*Problem is here*

End If

lReturn已在开头包含Order By,这是一个Lambda表达式。如果用户不是admin,则最后一个Linq查询由于某种原因不包括order。 我正在使用sql profiler来查明查询的外观,如下所示

exec sp_executesql N'SELECT 
[Extent1].[ID] AS [ID], 
[Extent1].[Name] AS [Name], 
.........
[Extent1].[SortOrder] AS [SortOrder]
FROM  [dbo].[Inventories] AS [Extent1]
LEFT OUTER JOIN [dbo].[AssignService] AS [Extent2] ON ([Extent1].[ID] = [Extent2].[Id]) AND ([Extent2].[AgentId] = @p__linq__0)
WHERE (0 = [Extent1].[AdminOnly]) AND ([Extent2].[Assign] = 1 OR [Extent1].[isVisibleToAllAgents] = 1) ,N'@p__linq__0 int',@p__linq__0=112

这是一种常规行为吗?还是我错过了什么?

1 个答案:

答案 0 :(得分:0)

基于LINQ的ORM已经放弃了关于支持模式的特定顺序的规则。总是支持的(根据我的经验)是在查询结束时只使用其后的Where和Select操作进行排序。

订单可能会在加入时丢失。我并不感到惊讶。