如何使用LINQ和EF查找层次结构的根?

时间:2012-12-02 11:28:11

标签: sql-server entity-framework sql-server-2005 entity-framework-4 entity-framework-5

我已成功使用问题Hierarchical data in Linq - options and performance的已接受答案来查询特定记录/节点的所有后代的分层表。现在我需要找到特定节点是其后代的树的根。我如何使用尽可能接近的解决方案来做到这一点?

层次结构由具有ParentId列的自引用表表示,对于层次结构中的顶级项,该列为空。

1 个答案:

答案 0 :(得分:0)

这是你正在寻找的那种东西

CREATE TABLE [dbo].[hierarchical_table](
    [id] INT,
    [parent_id] INT,
    [data] VARCHAR(255)
)
GO

INSERT [dbo].[hierarchical_table]
SELECT 1,NULL,'/1' UNION ALL
SELECT 2,1,'/1/2' UNION ALL
SELECT 3,2,'/1/2/3' UNION ALL
SELECT 4,2,'/1/2/4' UNION ALL
SELECT 5,NULL, '/5' UNION ALL
SELECT 6,5,'/5/6'
GO

CREATE FUNCTION [dbo].[fn_root_for_node] 
(
    @id int
)
RETURNS TABLE AS
RETURN (
    WITH [hierarchy_cte](id, parent_id, data, [Level]) AS
    (
        SELECT
            id,
            parent_id,
            data,
            0 AS [Level]
        FROM dbo.hierarchical_table
        WHERE id = @id
        UNION ALL
        SELECT t1.id, t1.parent_id, t1.data, h.[Level] + 1 AS [Level]
        FROM  dbo.hierarchical_table AS t1
        INNER JOIN hierarchy_cte AS h
            ON t1.id = h.parent_id
    )
    SELECT TOP 1
        id, parent_id, data, [Level]
    FROM [hierarchy_cte]
    ORDER BY [Level] DESC
)
GO

SELECT * FROM [dbo].[fn_root_for_node] (6)
GO