Sql 在EntityFramework 5中使用公共表表达式

Sql 在EntityFramework 5中使用公共表表达式,sql,entity-framework,common-table-expression,Sql,Entity Framework,Common Table Expression,我首先使用EF5代码,我有一个标准的树类型结构,它是一组嵌套的文件夹s。某些文件夹中有设备s。我想做的是能够选择一个文件夹,并找到该文件夹及其子文件夹中的所有设备 经过一些挖掘,我似乎需要使用公共表表达式来生成所需的数据。不幸的是,我真的很难做到这一点 public class Folder { public virtual ICollection<Folder> Children { get; set; } public virtual ICollection<

我首先使用EF5代码,我有一个标准的类型结构,它是一组嵌套的文件夹s。某些文件夹中有
设备
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; }
 }
一旦这被排除,我也不知道如何准确地构建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(选择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
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