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

将包含“with”cte的sql语句转换为linq,linq,common-table-expression,Linq,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 C

我这里有一段代码,已经和它斗争了几个小时。基本上,此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
此查询将返回如下内容:

Id |姓名|家长Id 1 | StartFolder |空 2 |折叠2 | 1 4 |折叠3 | 1 5 |折叠4 | 4
现在我想把代码转换成linq。我知道它涉及某种形式的递归,但由于with语句,它仍然被卡住了

没有Linq到SQL的等价物能够以高效的方式做到这一点。最好的解决方案是从包含该语句的Linq调用SP/View/UDF。

您可以编写递归或非递归代码,反复查询数据库,直到它得到所有结果为止

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

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

有一个已知的插件“LinqToDb”,它提供了在Linq中获得等效CTE的方法,这将为树结构中的每个节点调用DB。是的,但我必须抵制所有SP和实际SQL代码。在这种情况下别无选择为什么?!既然已经有了好的解决方案,为什么还要写坏代码呢。你知道Linq最终还是会生成SQL吗?我通常在大多数数据访问查询中使用Linq,但当需要高性能时,我总是直接编写SQL。代码中针对db上下文的Sql查询可以很好地映射到Linq实体。啊,我现在明白你的意思了,非常感谢你的提示!