从数据库构建JSON层次结构

时间:2015-09-14 13:14:31

标签: c# asp.net json asp.net-mvc entity-framework

C#| .NET 4.5 |实体框架5

我以ID,RoleName,ParentId的形式从SQL查询返回数据。我想获取该数据并将其解析为Hierarchical JSON字符串。到目前为止,它似乎更应该是一项艰巨的任务。因为我正在使用Entity,所以数据作为IEnumerable很好地回馈给我。现在我相信我只需要某种形式的递归,但我不太清楚从哪里开始。任何帮助表示赞赏。

数据返回

    id   parentId    name
1   1      Null       ED
2   2      1          CPD
3   3      2          Centre Manager 
4   4      3          Manager
5   5      4          Sales Head
6   6      4          Technical Head
7   7      5          Sales Individual
8   8      6          Technical Individual

代码

public ActionResult getJsonTree()
{
    var roles = getChilds(null).ToArray();
    return Json(roles, JsonRequestBehavior.AllowGet);
}

private IEnumerable<RoleVM> getChilds(int? parentID)
{
    return _db.Roles
        .Where(r => r.ParentID == parentID)
        .Select(x =>
                new RoleVM()
                {
                    text=x.RoleName,
                    icon = "glyphicon glyphicon-user",
                    node=getChilds(x.Id)
                }).ToList();
}

模型类

public partial class Role
{
  public int Id { get; set; }
  public string RoleName { get; set; }
  public Nullable<int> ParentID { get; set; }
}

public class RoleVM
{
  public string text { get; set; }
  public string icon { get; set; }
  public IEnumerable<RoleVM> node { get; set; }
}

我希望最终的结果是这样的:

var tree = [{
  text: "ED",
  icon: "glyphicon glyphicon-user",
  nodes: [{
    text: "CPD",
    icon: "glyphicon glyphicon-user",
    nodes: [{
      text: "Center Manager",
      icon: "glyphicon glyphicon-user",
      nodes: [{
        text: "Manager",
        icon: "glyphicon glyphicon-user",
        nodes: [{
          text: "Tech Head",
          icon: "glyphicon glyphicon-user",
          nodes: [{
            text: "Individual",
            icon: "glyphicon glyphicon-user",
          }]
        }]

      }]

    }]
  }]
}];

我得到的内容如下

[

  {

    "text": "ED",
    "icon": "glyphicon glyphicon-user",
    "node": null

  }, {

    "text": "CPD",
    "icon": "glyphicon glyphicon-user",
    "node": null

  }, {

    "text": "Centre Manager",
    "icon": "glyphicon glyphicon-user",
    "node": null

  }, {

    "text": "Manager",
    "icon": "glyphicon glyphicon-user",
    "node": null

  }, {

    "text": "Tech Head",
    "icon": "glyphicon glyphicon-user",
    "node": null

  },

  {
    "text": "Individual",
    "icon": "glyphicon glyphicon-user",
    "node": null
  }

]

0 个答案:

没有答案