将包含'with'cte的sql语句转换为linq

sch*_*h55 5 sql linq with-statement common-table-expression

嘿,我这里有这段代码,与它斗争了好几个小时.这个sql语句的作用基本上是获取指定文件夹的所有子文件夹(@compositeId).

WITH auto_table (id, Name, ParentID) AS
(
SELECT
    C.ID, C.Name, C.ParentID
FROM Composite_Table AS C
    WHERE C.ID = @compositeId

UNION ALL

SELECT
    C.ID, C.Name, C.ParentID
FROM Composite_Table AS C
    INNER JOIN auto_table AS a_t ON C.ParentID = a_t.ID
)

SELECT * FROM auto_table
Run Code Online (Sandbox Code Playgroud)

此查询将返回如下内容:

  • Id | 名称| 的ParentId
  • 1 | StartFolder | 空值
  • 2 | Folder2 | 1
  • 4 | Folder3 | 1
  • 5 | Folder4 | 4

现在我想将代码转换为linq.我知道它涉及某种形式的递归,但仍然因为with语句而停滞不前.救命?

sch*_*h55 -1

public static List<Composite> GetSubCascading(int compositeId)
{
    List<Composite> compositeList = new List<Composite>();

    List<Composite> matches = (from uf in ctx.Composite_Table
    where uf.Id == compositeId
    select new Composite(uf.Id, uf.Name, uf.ParentID)).ToList();

    if (matches.Any())
    {
        compositeList.AddRange(TraverseSubs(matches));
    }

    return compositeList;
}

private static List<Composite> TraverseSubs(List<Composite> resultSet)
{
    List<Composite> compList = new List<Composite>();

    compList.AddRange(resultSet);

    for (int i = 0; i < resultSet.Count; i++)
    {
        //Get all subcompList of each folder
        List<Composite> children = (from uf in ctx.Composite_Table
        where uf.ParentID == resultSet[i].Id
        select new Composite(uf.Id, uf.Name, uf.ParentID)).ToList();

        if (children.Any())
        {
            compList.AddRange(TraverseSubs(children));
        }
    }

    return compList;
}

//All where ctx is your DataContext
Run Code Online (Sandbox Code Playgroud)