我使用的是 EF5 Code First,我有一个标准Tree
类型结构,它是一堆嵌套Folder
的 s。有些文件夹Device
里面有 s。我想要做的是能够选择一个文件夹并找到该文件夹及其子文件夹中的所有设备。
经过一番挖掘,我似乎需要使用通用表表达式来生成我需要的数据。不幸的是,我真的很难做到这一点。
public class Folder
{
public virtual ICollection<Folder> Children { get; set; }
public virtual ICollection<Device> Devices { get; set; }
}
public class Device
{
public virtual ICollection<Folder> PresentInFolders { get; set; }
}
我试图根据这篇 MSDN 文章GetDevicesForFolderRecursively
上的工作添加一个功能。该查询不完整,因为在我的情况下不起作用,因为设备可以位于多个文件夹中,因此它有一个文件夹列表。folder.FolderId equals device.FolderID
public IQueryable<Device> GetDevicesForFolderRecursively(int folderID)
{
return from folder in this.FlatFolders
join device in this.Devices on folder.FolderId equals device.FolderID
where folder.FolderId == folderID
select device;
}
一旦解决了这个问题,我也不知道如何准确地构建 CTE。MSDN 文章创建的 CTE 看起来像这样,但我不知道如何根据我的需要对其进行修改,以及这将如何递归工作?
context.Database.ExecuteSqlCommand(@"CREATE VIEW [dbo].[ManagerEmployees]
AS
WITH cte ( ManagerEmployeeID, EmployeeID )
AS ( SELECT EmployeeID ,
EmployeeID
FROM dbo.Employees
UNION ALL
SELECT e.EmployeeID ,
cte.EmployeeID
FROM cte
INNER JOIN dbo.Employees AS e ON e.ReportsToEmployeeID = cte.ManagerEmployeeID
)
SELECT ISNULL(EmployeeID, 0) AS ManagerEmployeeID ,
ISNULL(ManagerEmployeeID, 0) AS EmployeeID
FROM cte");
更新
我已经设法使 CTE 查询达到这种状态,但仍然无法正常工作。它不明白AS ( SELECT FolderId , [EstateManagerService].dbo.Devices.DeviceSerial
,我不确定那里的价值是什么?
CREATE VIEW [dbo].[ManagerEmployees]
AS
WITH cte ( FolderID, DeviceID )
AS ( SELECT FolderId ,
[EstateManagerService].dbo.Devices.DeviceSerial
FROM [EstateManagerService].dbo.Folders
UNION ALL
SELECT e.Folder_FolderId,
cte.FolderID
FROM cte
INNER JOIN [EstateManagerService].dbo.FolderDevices AS e ON e.Folder_FolderId = cte.FolderID
)
SELECT ISNULL(DeviceID, 0) AS FolderID ,
ISNULL(FolderID, 0) AS DeviceID
FROM cte