Database Reference
In-Depth Information
Listing 2-7. Inserting into Our Model and Recursively Enumerating All of the Instances of the Self-referencing entity
static void RunExample()
{
using (var context = new EF6RecipesContext())
{
var louvre = new PictureCategory { Name = "Louvre" };
var child = new PictureCategory { Name = "Egyptian Antiquites" };
louvre.Subcategories.Add(child);
child = new PictureCategory { Name = "Sculptures" };
louvre.Subcategories.Add(child);
child = new PictureCategory { Name = "Paintings" };
louvre.Subcategories.Add(child);
var paris = new PictureCategory { Name = "Paris" };
paris.Subcategories.Add(louvre);
var vacation = new PictureCategory { Name = "Summer Vacation" };
vacation.Subcategories.Add(paris);
context.PictureCategories.Add(paris);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
var roots = context.PictureCategories.Where(c => c.ParentCategory == null);
roots.ForEach(root => Print(root, 0));
}
}
static void Print(PictureCategory cat, int level)
{
StringBuilder sb = new StringBuilder();
Console.WriteLine("{0}{1}", sb.Append(' ', level).ToString(), cat.Name);
cat.Subcategories.ForEach(child => Print(child, level + 1));
}
The output of the code in Listing 2-7 shows our root node: Summer Vacation. The first (and only) child is Paris.
Paris has Louvre as a child. Finally, at the Louvre, we categorized our pictures by the various collections we visited.
Summer Vacation
Paris
Louvre
Egyptian Antiquities
Sculptures
Paintings
Clearly, the code is a little involved. We start by creating and initializing the instances of our entity types. We wire
them together in the object graph by adding the PictureCategories to our louvre category. Then we add the louvre
category to the paris category. Finally, we add the paris category to our summer vacation category. We build the
hierarchy from the bottom up.
 
Search WWH ::




Custom Search