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

时间:2011-05-03 22:20:13

标签: sql linq common-table-expression with-statement

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

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

此查询将返回如下内容:

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

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

4 个答案:

答案 0 :(得分:3)

没有Linq to SQL等效可以做到这一点(以有效的方式)。最好的解决方案是从Linq调用包含该语句的SP / View / UDF。

答案 1 :(得分:1)

您可以编写重复查询数据库的代码(递归与否),直到它具有所有结果。

但我认为没有办法编写单个LINQ to SQL查询,可以一次性获得所需的所有结果,因此最好将查询保留在SQL中。

答案 2 :(得分:0)

有一个已知的插件“ LinqToDb ”,该插件提供了在Linq中获得等效CTE的方法

答案 3 :(得分:-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
相关问题