我想将以下查询(正常工作)从查询语法转换为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语法,但结果总是空值:
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();
}
您在父对象上有子对象的集合吗?如果你的关系被映射了,你应该这样做。在这种情况下,您可以尝试:
var query = from dbFolder in db.FileStorageFolders
from subFolder in dbFolder.SubFolders // Here I use that mapped relations
where ...
select new { ... };
查询的问题是您正在创建匿名类型并将其转换为您的类型,这是不可能的。此外,它也不是完整的分层查询(您的SQL也不是)。它将只选择一个级别的子文件夹。