SqlServer与Linq 无限递归目录树且输出层级

时间:2023-02-03 05:08:34
ALTER VIEW [dbo].[view_TreeLevel]
AS
WITH cte
AS (
SELECT a.ModuleID ,
a.Module_Name ,
a.Module_Description ,
a.Module_FatherID ,
a.Module_Url ,
a.Module_Order, 1 Level FROM TT_TreeView a WHERE a.Module_FatherID=0
UNION ALL
SELECT b.ModuleID ,
b.Module_Name ,
b.Module_Description ,
b.Module_FatherID ,
b.Module_Url ,
b.Module_Order, Level+1 FROM TT_TreeView b INNER JOIN cte c ON b.Module_FatherID = c.ModuleID
)
SELECT TOP 100 PERCENT * FROM cte ORDER BY Level

SqlServer与Linq 无限递归目录树且输出层级

CREATE TABLE [dbo].[AreaTable](
[Id] int PRIMARY KEY IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Parent] int NOT NULL,
)
GO INSERT INTO [AreaTable]
SELECT '中国',0 UNION ALL
SELECT '广东',1 UNION ALL
SELECT '湖南',1 UNION ALL
SELECT '深圳',2 UNION ALL
SELECT '长沙',3 UNION ALL
SELECT '福田',4 UNION ALL
SELECT '南山',4 UNION ALL
SELECT '天心',5 UNION ALL
SELECT '岳麓',5 UNION ALL
SELECT '芙蓉',5 UNION ALL
SELECT '蛇口',7 UNION ALL
SELECT '科技园',7
GO --查询全国
WITH temp
AS
(
SELECT *,1 Level FROM [AreaTable] WHERE Parent = 1 --1全国 2广东
UNION ALL
SELECT m.*,Level+1 FROM [AreaTable] AS m
INNER JOIN temp AS child ON m.Parent = child.Id
)
SELECT * FROM temp ORDER BY temp.Level

SqlServer与Linq 无限递归目录树且输出层级

void Main()
{
var query = GetChildren(2); //Linq递归查询方法
Console.WriteLine("Id\tName\tParent");
query.ToList().ForEach(q => Console.WriteLine("{0}\t{1}\t{2}", q.Id, q.Name, q.Parent));
} private IEnumerable<AreaTable> GetChildren(int p_id)
{
var query = RBAC.Dal.DataRootBase.Context.From<AreaTable>().Where(p => p.Parent == p_id);
return query.ToList().Concat(query.ToList().SelectMany(t => GetChildren(t.Id)));
}

SqlServer与Linq 无限递归目录树且输出层级