需要帮助将CTE查询转换为linq(非递归)
当您不知道SQL查询背后的数据时,我不确定仅通过查看示例SQL查询来回答这个问题有多容易,但我还是会尝试。这是一个SQL查询,用于列出源代码管理数据库中的文件——将源文件路径与其最近签入的版本路径并排显示:需要帮助将CTE查询转换为linq(非递归),linq,common-table-expression,Linq,Common Table Expression,当您不知道SQL查询背后的数据时,我不确定仅通过查看示例SQL查询来回答这个问题有多容易,但我还是会尝试。这是一个SQL查询,用于列出源代码管理数据库中的文件——将源文件路径与其最近签入的版本路径并排显示: WITH [recentCheckins] AS ( SELECT [SourceFileID], MAX([Version]) AS [LatestVersion] FROM [Checkin] GROUP BY [SourceFileID] ) SELE
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
};
正如上面Gert所建议的那样,通过将其分解为单独的查询来实现这一点。使用CTE的查询是递归的。Linq不能在一条语句中执行递归查询。您必须单独查询每个级别,或者查看递归查询,并将其用作linq的数据源。我想我不明白在CTE上下文中递归意味着什么,但谢谢您,我能够通过按照您的建议编写单独的查询来解决问题。