I currently have data in a SQL table that contains a ConfigHead table and a Config Line Table. The Config Line table is a self referencing table. My new data structure has the ConfigLines that has a collection of ConfigLines, i am trying to recursively walk through the records and add a children ConfigLines to the parent ConfigLines collection. This is what i currently have....
Here is the data structure
ConfigHead
ConfigLine
As you can see the ConfigLine table has a ParentConfigLineId which references itself. If the ParentConfigLineId is 0 then that means it's a top level item.
Here is the shape of my Data Model that i am trying to get the data in.
public class ConfigLine
{
public int Id { get; set; }
public int ConfigHeadId { get; set; }
public int ParentCongigLineId { get; set; }
public List<ConfigLine> Children { get; set; }
}
public class ConfigHeader
{
public int Id { get; set; }
public List<ConfigLine> ConfigLines { get; set; }
}
At the moment i am trying to recursively walk through the Config Lines but i'm not sure how to then add it to the parent list. This is what i have so far.
public void Get(int id)
{
//Main ConfigHeader Record
var configHeader = new ConfigHead();
//Get the record from the db
var configRecord = _configRepository
.GetAll()
.Include(p => p.ConfigLines)
.Where(x => x.Id == id).FirstOrDefault();
//Loop the top level config lines
foreach (var configLine in configRecord.ConfigLines.Where(x => x.ParentConfigLineId == 0))
{
if (configLine.ParentConfigLineId == 0)
{
//Add the Top Level Config line
var topLevel = new ConfigLine
{
Id = configLine.Id,
ConfigHeadId = configLine.ConfigHeadId,
ParentCongigLineId = configLine.ParentConfigLineId
};
configHeader.children.Add(topLevel);
//Check the top level ConfigLine to see if it has any children.
var topLevelConfigLines = configRecord.ConfigLines
.Where(x => x.ParentConfigLineId == configLine.Id)
.ToList();
if (topLevelConfigLines.Any())
{
AddChildConfigLine(configRecord, configLine);
}
}
}
}
This is my recursive method - I'm stuck on how to walk down the collection and then add them to the parent item.
private void AddChildConfigLine(ConfigRecord configRecord,
ConfigLine configLine)
{
//Check for any child records
var childConfigLines = configRecord.ConfigLines.Where(x => x.ParentConfigLineId == configLine.Id);
foreach (var childConfigLine in childConfigLines)
{
//How to add to the collection?
AddChildConfigLine(configRecord, childConfigLine);
}
}