为什么这个LINQ TO SQL查询不会以正确的顺序返回?

时间:2009-11-30 18:31:02

标签: c# linq-to-sql

(from assetVisit in AssetVisits
                        join assetBundle in AssetBundles on assetVisit.AssetID equals assetBundle.AssetID
                        join groupBundle in GroupBundles on assetBundle.BundleID equals groupBundle.BundleID
                        join userGroup in UserGroups on groupBundle.GroupID equals userGroup.GroupID
                        where assetVisit.CompanyID == 32 &&
                              userGroup.UserID == 75
                        orderby assetVisit.AccessCounter descending
                        select assetVisit).Distinct()

注意'order by'然而,当数据回来时,它是由assetVisit表的PK命令的,是什么给出的?

SQL PER LINQPAD:

-- Region Parameters
DECLARE @p0 Int SET @p0 = 32
DECLARE @p1 Int SET @p1 = 75
-- EndRegion
SELECT DISTINCT [t0].[AssetVisitID], [t0].[CompanyID], [t0].[AssetID], [t0].[AccessCounter], [t0].[CreateBy], [t0].[CreateDate], [t0].[ModifyBy], [t0].[ModifyDate]
FROM [AssetVisits] AS [t0]
INNER JOIN [AssetBundles] AS [t1] ON [t0].[AssetID] = ([t1].[AssetID])
INNER JOIN [GroupBundles] AS [t2] ON ([t1].[BundleID]) = [t2].[BundleID]
INNER JOIN [UserGroups] AS [t3] ON [t2].[GroupID] = [t3].[GroupID]
WHERE ([t0].[CompanyID] = @p0) AND ([t3].[UserID] = @p1)

2 个答案:

答案 0 :(得分:3)

您的“order by”应该之后

    (from assetVisit in AssetVisits
     join assetBundle in AssetBundles on assetVisit.AssetID equals assetBundle.AssetID
     join groupBundle in GroupBundles on assetBundle.BundleID equals groupBundle.BundleID
     join userGroup in UserGroups on groupBundle.GroupID equals userGroup.GroupID
     where assetVisit.CompanyID == 32 &&
               userGroup.UserID == 75
     select assetVisit).Distinct().OrderByDescending(assetVisit => assetVisit.AccessCounter);

或者如果您希望继续使用查询语法,可以这样写:

    var innerQuery =
        (from assetVisit in AssetVisits
         join assetBundle in AssetBundles on assetVisit.AssetID equals assetBundle.AssetID
         join groupBundle in GroupBundles on assetBundle.BundleID equals groupBundle.BundleID
         join userGroup in UserGroups on groupBundle.GroupID equals userGroup.GroupID
         where assetVisit.CompanyID == 32 &&
                   userGroup.UserID == 75
         select assetVisit).Distinct();

    var query = from assetVisit in innerQuery
            orderby assetVisit.AccessCounter descending
            select assetVisit;

答案 1 :(得分:0)

我之前碰到过这个。不同的运算符“撤消”您之前在LINQ语句中指定的任何排序。

这是一个很好的解释: http://programminglinq.com/blogs/marcorusso/archive/2008/07/20/use-of-distinct-and-orderby-in-linq.aspx