简体   繁体   English

从自引用数据库表中填充递归数据结构

[英]Fill a Recursive Data Structure from a Self-Referential Database Table

This question refers to http://www.matthidinger.com/archive/2009/02/08/asp.net-mvc-recursive-treeview-helper.aspx 这个问题涉及http://www.matthidinger.com/archive/2009/02/08/asp.net-mvc-recursive-treeview-helper.aspx

Let's say I have a table that looks like this: 假设我有一个看起来像这样的表:

替代文字
(source: matthidinger.com ) (来源: matthidinger.com

And I have a recursive data structure that looks like this: 我有一个递归数据结构,如下所示:

public class TreeNode
{
    public TreeNode(){}
    public string NodeId { get; set; }
    public string ParentId { get; set; }
    public string Name { get; set; }
    public IEnumerable<TreeNode> Children { get; }
}

How do I fill this recursive data structure from the table using Linq? 如何使用Linq从表中填充此递归数据结构?

NOTE: For purposes of this question, please assume that I already have a perfectly efficient table; 注意:出于这个问题的目的,请假设我已经有一个非常有效的表格; ie it is completely resident in memory, or it is being access using a CTE. 即它完全驻留在内存中,或者使用CTE进行访问。 Really, I am just looking for the Linq queries to get it from the Linq to SQL DataContext to the recursive object. 真的,我只是在寻找Linq查询,以便从Linq到SQL DataContext到递归对象。 I am aware it will probably involve a ForEach and a recursive function call; 我知道它可能涉及ForEach和递归函数调用; I just can't quite get my head around it. 我只是无法理解它。

Thanks in advance. 提前致谢。

I think your best option is to query the hierachy in SQL using CTEs. 我认为您最好的选择是使用CTE查询SQL中的层次结构。 LINQ2SQL and hierachical/relational data don't mix too nicely. LINQ2SQL和层次/关系数据混合得不太好。 See Hierarchical data in Linq - options and performance . 请参阅Linq中的分层数据 - 选项和性能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM