使用C#/ Linq将展平的分层数据从SQL Server转换为结构化JSON对象

Jus*_*tch 3 linq asp.net-mvc json entity-framework

我正在开发一个MVC应用程序,它从SQL Server中的表中检索数据,结构如下:

+-----------------------------------+
| Id | Name   | Hierarchy   | Depth |
|-----------------------------------|
| 01 | Justin | /           |     0 |
| 02 | Chris  | /1          |     1 |
| 03 | Beth   | /1/1        |     2 |
+-----------------------------------+
Run Code Online (Sandbox Code Playgroud)

Hierarchy列中的示例数据是hierarchyid数据类型的字符串表示形式,并Depth使用该hierarchyid::GetLevel()方法计算列.

使用Entity Framework 4.1,我已将上表映射到此类:

public class Node {
    public int Id { get; set; }
    public string Name { get; set; }
    public string HierarchyPath { get; set; } // String representation of the hierarchyid
    public int Depth { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想使用此信息来使用JS Visualizations Toolkit向用户显示层次结构的图形表示,这需要构建数据:

var node = {
    id: 1,
    name: 'Justin'
    children: [{
        id: 2,
        name: 'Chris',
        children: [{
            id: 3,
            name: 'Beth',
            children: []
        }]
    }]
}
Run Code Online (Sandbox Code Playgroud)

我在开发逻辑以将我的模型列表转换为结构化JSON对象时遇到了麻烦.有什么建议?

Jon*_*eet 7

编辑:我现在没有时间来解决下面的答案,但考虑到问题中的额外信息,我怀疑你想保留一个Dictionary<int, HierarchicalNode>而不是一个List<HierarchicalNode>,以至于你不依赖于任何订购......


我会忘记开始的JSON表示,并专注于构建层次结构的内存中POCO表示.要做到这一点,我会使用这样的东西:

class HierarchicalNode
{
    private readonly List<HierarchicalNode> children =
        new List<HierarchicalNode>();        
    public List<HierarchicalNode> Children { get { return children; } }

    private readonly string name;
    public string Name { get { return name; } }

    private readonly int id;
    public int Id { get { return id; } }

    public HierarchicalNode(string name, int id)
    {
        this.name = name;
        this.id = id;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样构建树:

// Make sure we get everything in a sensible order, parents before children
var query = context.Nodes.OrderBy(x => x.Depth);

var root = new HierarchicalNode("Root", 0);
foreach (var node in query)
{       
    var current = root;
    foreach (string part = node.HierarchyPath.Split(new[] {'/'},
                                   StringSplitOptions.RemoveEmptyEntries))
    {
        int parsedPart = int.Parse(part);
        current = current.Children[parsedPart - 1];
    }
    current.Children.Add(new HierarchicalNode(node.Name, node.Id));
}
Run Code Online (Sandbox Code Playgroud)

  • @JustinRusbatch:感谢您发布此问题.这正是我想要的.有没有机会发布解决方案?如果你也可以发布解决方案,那就太棒了!!!!!! (2认同)