需要帮助将CTE查询转换为linq(不是递归的)

时间:2013-02-24 02:28:23

标签: linq common-table-expression

当你不知道它背后的数据时,不知道通过查看示例SQL查询来回答这是多么容易,但我还是会尝试。这是一个SQL查询,用于列出源控件数据库中的文件 - 显示与最新签入版本路径并排的源文件路径:

WITH [recentCheckins] AS (
    SELECT [SourceFileID], MAX([Version]) AS [LatestVersion]
    FROM [Checkin]
    GROUP BY [SourceFileID]     
) SELECT 
    [sf].[Path], -- current version
    [ci].[ArchivePath] -- most recent previous checkin
FROM 
    [recentCheckins] 
    INNER JOIN [SourceFile] [sf] ON [recentCheckins].[SourceFileID]=[sf].[ID]
    INNER JOIN [Checkin] [ci] ON 
        [recentCheckins].[SourceFileID]=[ci].[SourceFileID] AND
        [recentCheckins].[LatestVersion]=[ci].[Version]

这是我能做的最多:

var query2 =
    from latestCheckins in (
         from checkin in _project.Checkin
         group checkin by checkin.SourceFileID into results
         select new
         {
             SourceFileID = results.Key,
             LatestCheckinVersion = results.Max(s => s.Version)
         })
         join sourceFile in _project.SourceFile on latestCheckins.SourceFileID equals sourceFile.ID
         join checkins in _project.Checkin on // fails on this line, does not like join keyword here
             new { latestCheckins.SourceFileID, latestCheckins.LatestCheckinVersion }               
                  equals new { checkins.SourceFileID, checkins.Version }
             select new
             {
                Filename = sourceFile.Path,
                CheckinDate = checkins.DateCreated,
                TaskID = checkins.TaskID,
                Comments = checkins.Comments,
                Version = latestCheckins.LatestCheckinVersion.ToString(),
                NewFile = _project.GetSourceFilename(sourceFile.Path),
                OldFile = checkins.ArchivePath,
                ID = sourceFile.ID
             };

1 个答案:

答案 0 :(得分:1)

通过将其分解为单独的查询来实现这一点,正如Gert上面所建议的那样。