简体   繁体   中英

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

Let's say I have a table that looks like this:

替代文字
(source: 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?

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. Really, I am just looking for the Linq queries to get it from the Linq to SQL DataContext to the recursive object. I am aware it will probably involve a ForEach and a recursive function call; 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. LINQ2SQL and hierachical/relational data don't mix too nicely. See Hierarchical data in Linq - options and performance .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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