gpt4 book ai didi

asp.net-mvc - 使用 C#/Linq 将来自 SQL Server 的扁平化分层数据转换为结构化的 JSON 对象

转载 作者:行者123 更新时间:2023-12-03 20:23:15 25 4
gpt4 key购买 nike

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

+-----------------------------------+
| Id | Name | Hierarchy | Depth |
|-----------------------------------|
| 01 | Justin | / | 0 |
| 02 | Chris | /1 | 1 |
| 03 | Beth | /1/1 | 2 |
+-----------------------------------+
Hierarchy中的示例数据column 是 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; }
}

我想使用此信息向使用 JS Visualizations Toolkit 的用户显示层次结构的图形表示。 ,这需要对数据进行结构化:
var node = {
id: 1,
name: 'Justin'
children: [{
id: 2,
name: 'Chris',
children: [{
id: 3,
name: 'Beth',
children: []
}]
}]
}

我在开发将模型列表转换为结构化 JSON 对象的逻辑时遇到问题。有什么建议?

最佳答案

编辑:我现在没有时间修复下面的答案,但鉴于问题中的额外信息,我怀疑您想保留 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;
}
}

然后像这样构建树:
// 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));
}

关于asp.net-mvc - 使用 C#/Linq 将来自 SQL Server 的扁平化分层数据转换为结构化的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6945216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com