LINQ to SQL递归问题

时间:2011-06-23 07:41:48

标签: c# linq-to-sql recursive-query

我想将以下查询(工作正常)从查询语法转换为LINQ语法,但我似乎无法做到正确:

SELECT
    [t1].[ID], [t1].[ParentID], [t1].[FolderName],
    [t1].[Purpose], [t1].[IsSystem],t1].IsHidden],
    [t1].[ChangeSrc], [t1].[SyncGUID], [t1].[CreationDBTimeStamp]
FROM [dbo].[FileStorageFolders] AS [t0]
INNER JOIN [dbo].[FileStorageFolders] AS [t1] ON ([t0].[ID]) = [t1][ParentID]
WHERE ([t1].[Purpose] = @p0)
    AND ([t1].[FolderName] = @p1)
    AND ([t0].[ParentID] IS NULL)
    AND ([t0].[Purpose] = @p2)

我使用此LINQ语法,但结果始终为null值:

 private static FileStorageFolder GetCapsuleContentFolder(FileStorageDataContext db)
    {    IQueryable<FileStorageFolder> source = (from dbfolder in db.FileStorageFolders
            join dbsubfolder in db.FileStorageFolders on
                new { ParentID = dbfolder.ID } equals
                new { ParentID = Convert.ToInt32(dbsubfolder.ParentID) }
            where
                dbfolder.ParentID == null &&
                dbfolder.Purpose == 'REPORT' &&
                dbsubfolder.Purpose == 'LayoutFolder' &&
                dbsubfolder.FolderName == 'LayoutReport'
            select new
                    {
                        dbsubfolder.ID,
                        ParentID = (System.Int32?)dbsubfolder.ParentID,
                        dbsubfolder.FolderName,
                        dbsubfolder.Purpose,
                        dbsubfolder.IsSystem,
                        pqrentID2 = dbfolder.ParentID,
                        Purpose2 = dbfolder.Purpose
                    }) as IQueryable<FileStorageFolder>;
return source.Single();
}

1 个答案:

答案 0 :(得分:0)

您是否在父母身上收集了儿童费用?如果您的关系已映射,则应该。在这种情况下,您可以尝试:

var query = from dbFolder in db.FileStorageFolders
            from subFolder in dbFolder.SubFolders // Here I use that mapped relations
            where ...
            select new { ... };

您的查询的问题是您正在创建匿名类型并将其转换为您的类型 - 这是不可能的。此外,它不是完整的分层查询(您的SQL不是很好)。它只会选择一个级别的子文件夹。