C# | .NET 4.5 | Entity Framework 5
I have data coming back from a SQL Query in the form of ID,RoleName,ParentId. I'd like to take that data and parse it into a Hierarchical JSON string. So far it seems to be much more of a daunting task than it should be. Since I'm using Entity the data comes back nicely to me as an IEnumerable. Now I believe I just need some form of recursion, but I'm not quite sure where to start. Any help is appreciated.
Data Returns as
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
Code Is
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();
}
Model Class is
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; }
}
The end result I'd hope would be something like this:
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",
}]
}]
}]
}]
}]
}];
What I am getting is as follows
[
{
"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
}
]