[英]Entity Framework Extensions Recursive Query
There is a hierarchical query support in a popular EF extensions library: https://entityframework-extensions.net/to-self-hierarchy-list .流行的 EF 扩展库中提供分层查询支持: https://entityframework-extensions.net/to-self-hierarchy-list 。
I'm curious how does it work under the hood?我很好奇它在引擎盖下是如何工作的? Is it getting handled by SQL server, meaning that the query is translated to CTE (common table expression)?它是否由 SQL 服务器处理,这意味着查询被转换为 CTE(公用表表达式)?
Disclaimer : I'm the owner of Entity Framework Extensions免责声明:我是实体框架扩展的所有者
You got it right, we indeed use a CTE in the generated SQL.你没看错,我们确实在生成的 SQL 中使用了 CTE。
Here is how looks the SQL template:这是 SQL 模板的外观:
WITH
SelfHierarchyQueryOuter AS (@(sqlMaster)),
SelfHierarchyQueryInner AS (@(sqlHierarchy)),
SelfHierarchyQuery AS (SELECT A.*, 0 AS ZZZ_Recursion FROM (SELECT * FROM SelfHierarchyQueryOuter) AS A
UNION ALL
SELECT B.*, ZZZ_Recursion + 1 AS ZZZ_Recursion FROM (SELECT * FROM SelfHierarchyQueryInner) AS B
INNER JOIN SelfHierarchyQuery AS C ON @(keyJoins)
WHERE ZZZ_Recursion < @(maxRecursion)
)
@(selectFinal)
FROM SelfHierarchyQuery
So a query like this one:所以像这样的查询:
var list2 = context.EntitySimples.ToSelfHierarchyList(x => x.Parent, options => options.MaxRecursion = 5);
Will generate the following SQL:会生成如下SQL:
WITH
SelfHierarchyQueryOuter AS (SELECT TOP 100 PERCENT
[Extent1].[ID] AS [ID],
[Extent1].[ColumnInt1] AS [ColumnInt1],
[Extent1].[ColumnInt2] AS [ColumnInt2],
[Extent1].[Parent_ID] AS [Parent_ID]
FROM [dbo].[EntitySimple] AS [Extent1]),
SelfHierarchyQueryInner AS (SELECT TOP 100 PERCENT
[Extent1].[ID] AS [ID],
[Extent1].[ColumnInt1] AS [ColumnInt1],
[Extent1].[ColumnInt2] AS [ColumnInt2],
[Extent1].[Parent_ID] AS [Parent_ID]
FROM [dbo].[EntitySimple] AS [Extent1]),
SelfHierarchyQuery AS (SELECT A.*, 0 AS ZZZ_Recursion FROM (SELECT * FROM SelfHierarchyQueryOuter) AS A
UNION ALL
SELECT B.*, ZZZ_Recursion + 1 AS ZZZ_Recursion FROM (SELECT * FROM SelfHierarchyQueryInner) AS B
INNER JOIN SelfHierarchyQuery AS C ON C.[Parent_ID] = B.[ID]
WHERE ZZZ_Recursion < 5
)
SELECT *
FROM SelfHierarchyQuery
Nothing "special" here, just using one great feature of the CTE to make it works.这里没有什么“特别的”,只是使用 CTE 的一项重要功能来使其工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.