linq2sql使不必要的ORDER BY

问题描述

| 我有一个复杂的linq2SQL查询,它不包含任何\'order by \'语句,但是linq2sql以某种方式认为这是必需的并插入它。不幸的是,这个“ order by”语句损害了性能,我不知道如何删除它。 这是linq2sql表达式(我认为它们可能没有帮助,但是无论如何...)
var lockedBy = Guid.NewGuid();
var locks = LinqDataContext.Instance.LockBranches(3,lockedBy,DateTime.Now + TimeSpan.FromMinutes(3)); // Stored procedure...

var x = LinqDataContext.Instance.Branches
.Where(branch => branch.LockedBy == lockedBy)
.Select
(
    branch => new
    {
        Branch = branch,Leaves = branch.Leaves
        .Select
        (
            leaf => new
            {
                Leaf = leaf,Estimate = leaf.Representation.Estimates
                .GroupBy(estimate=>estimate.SegmentID)
                .Sum
                (
                    estimatesBySegment => estimatesBySegment.Average
                    (
                        estimate => estimate.EstimateRequests.Average
                        (
                            estimateRequest => estimateRequest.EstimateSubmit.Value
                        )
                    )
                )
            }
        )
    }
);
它呈现给以下sql
SELECT [t0].[ID],[t0].[IndexID],[t0].[IndexNo],[t0].[Sealed],[t0].[LockedBy],[t0].[UnlockOn],[t1].[ID] AS [ID2],[t1].[BranchID],[t1].[RepresentationID],[t1].[Xml],(
    SELECT SUM([t7].[value])
    FROM (
        SELECT AVG([t6].[value]) AS [value]
        FROM (
            SELECT (
                SELECT AVG([t5].[Value])
                FROM [dbo].[EstimateRequests] AS [t4]
                LEFT OUTER JOIN [dbo].[EstimateSubmits] AS [t5] ON [t5].[EstimateRequestID] = [t4].[ID]
                WHERE [t4].[EstimateID] = [t3].[ID]
                ) AS [value],[t2].[ID],[t3].[RepresentationID],[t3].[SegmentID]
            FROM [dbo].[Representations] AS [t2],[dbo].[Estimates] AS [t3]
            ) AS [t6]
        WHERE ([t6].[ID] = [t1].[RepresentationID]) AND ([t6].[RepresentationID] = [t6].[ID])
        GROUP BY [t6].[SegmentID]
        ) AS [t7]
    ) AS [Estimate],(
    SELECT COUNT(*)
    FROM [dbo].[Leaves] AS [t8]
    WHERE [t8].[BranchID] = [t0].[ID]
    ) AS [value]
FROM [dbo].[Branches] AS [t0]
LEFT OUTER JOIN [dbo].[Leaves] AS [t1] ON [t1].[BranchID] = [t0].[ID]
WHERE [t0].[LockedBy] = @p0
ORDER BY [t0].[ID],[t1].[ID]  <-- Here\'s the unnecessary ORDER BY
    

解决方法

        需要
order by
才能区分子集合
Leaves
。 (每次您有一个孩子收藏时,都会有
order by
)