转换包含“with”的sql语句cte 到 linq
我这里有这段代码,已经与它斗争了几个小时。基本上,此 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 | Name | ParentId
1 | StartFolder| NULL
2 | Folder2 | 1
4 | Folder3 | 1
5 | Folder4 | 4
现在我想将代码转换为 linq。我知道它涉及某种形式的递归,但由于 with 语句,仍然卡住了。
I have this piece of code here, been battling with it for hours. basically what this sql statement does is gets ALL subfolders of a specified folder (@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
This query would return something like this:
Id | Name | ParentId
1 | StartFolder| NULL
2 | Folder2 | 1
4 | Folder3 | 1
5 | Folder4 | 4
Now I want to convert the code to linq. I know it involves some form of recursion but still stuck thanks to the with statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有 Linq to SQL 等效项可以(以有效的方式)做到这一点。最好的解决方案是从包含该语句的 Linq 调用 SP/View/UDF。
There is no Linq to SQL equivalent that can do that (in an efficient manner). Best solution would be to call a SP/View/UDF from Linq containing that statement.
您可以编写代码(无论是否递归)来重复查询数据库,直到获得所有结果。
但我认为没有办法编写一个 LINQ to SQL 查询来一次性获得所需的所有结果,因此最好将查询保留在 SQL 中。
You could write code (recursive or not) that repeatedly queries the database, until it has all the results.
But I think there is no way to write a single LINQ to SQL query that would get all the results you need in one go, so it's probably best to keep the query in SQL.
有一个已知的插件“LinqToDb”,它提供了在 Linq 中获取等效 CTE 的方法
There is known plugin 'LinqToDb', which provides methods to get CTE equivalent in Linq