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
此查询将返回如下内容:
现在我想将代码转换为linq。我知道它涉及某种形式的递归,但仍然因为with语句而停滞不前。帮助
答案 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