从自引用数据库表填充递归数据结构 [英] Fill a Recursive Data Structure from a Self-Referential Database Table

查看:65
本文介绍了从自引用数据库表填充递归数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题指的是 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:


(来源: matthidinger.com )


(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; }
}

如何使用Linq从表中填充此递归数据结构?

How do I fill this recursive data structure from the table using Linq?

注意::出于这个问题的目的,请假设我已经有一个非常有效的表格;即它完全驻留在内存中,或者正在使用CTE进行访问.确实,我只是在寻找Linq查询,以将其从Linq转换为SQL DataContext到递归对象.我知道它可能涉及一个ForEach和一个递归函数调用;我只是不太了解它.

NOTE: For purposes of this question, please assume that I already have a perfectly efficient table; i.e. 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.

谢谢.

推荐答案

我认为您最好的选择是使用CTE在SQL中查询层次结构. LINQ2SQL和层级/关系数据混合得不太好.请参阅 Linq中的分层数据-选项和性能.

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.

这篇关于从自引用数据库表填充递归数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆