I have a hierarchical class structure like this:
Category → Template → Instance
A category contains several templates, a template contains several instances.
If I request data from a database through a join across all 3 tables, the data looks something like this:
CategoryID | CategoryName | CategoryType | TemplateID | TemplateName | TemplateXYZ | InstanceID | InstanceName
1 | "CatA" | "TypeX" | 1 | "TempA" | "X" | 1 | "InstA"
1 | "CatA" | "TypeX" | 1 | "TempA" | "X" | 2 | "InstB"
1 | "CatA" | "TypeX" | 1 | "TempA" | "X" | 3 | "InstC"
1 | "CatA" | "TypeX" | 1 | "TempB" | "Y" | 4 | "InstD"
(just an example, real data tables contain a lot more columns)
What is the best / general way in C # to populate classes with this data type when cycling through it using a data reader?
At the top of my head, I would do it like this:
while(data.Read())
{
if(data["CategoryID"] != lastCategoryID) {
lastCategoryID = data["CategoryID"];
cat = new Category(data["CategoryName"], data["CategoryType"]);
catList.Add(cat);
}
if(data["TemplateID"] != lastTemplateID) {
lastTempateID = data["TemplateID"];
template = new Template(data["TemplateName"], data["TemplateXYZ"]));
cat.Templates.Add(template);
}
template.Instances.Add(new Instance(data["InstanceID"], data["InstanceName"]);
}
Is there a better, more elegant solution for populating hierarchical class objects? Perhaps using LINQ or dictionaries?
. . , .