linq2sql呈现不必要的ORDER BY

时间:2011-06-18 09:25:25

标签: c# linq-to-sql

我有一个复杂的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

1 个答案:

答案 0 :(得分:1)

需要order by才能区分子集合Leaves。 (每次有子集合时都有order by