Database Reference
In-Depth Information
Add a DbSet<PictureCategory> auto property to your DbContext subclass.
3.
4.
Override the OnModelCreating method in your DbContext class to configure the
bidirectional association (ParentCategory and SubCategories), as seen in Listing 2-6.
Listing 2-6. Overriding OnModelCreating in DbContext Subclass
public class EF6RecipesContext : DbContext
{
public DbSet<PictureCategory> PictureCategories { get; set; }
public PictureContext() : base("name=EF6CodeFirstRecipesContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<PictureCategory>()
.HasMany(cat => cat.SubCategories)
.WithOptional(cat => cat.ParentCategory);
}
}
How It Works
Database relationships are characterized by degree, multiplicity, and direction. Degree is the number of entity types
that participate in the relationship. Unary and binary relationships are the most common. Tertiary and n-place
relationships are more theoretical than practical.
Multiplicity is the number of entity types on each end of the relationship. You have seen the multiplicities 0..1
(zero or 1), 1 (one), and * (many).
Finally, the direction is either one-way or bidirectional.
The Entity Data Model supports a particular kind of database relationship called an Association Type .
An Association Type relationship has either unary or binary degree, multiplicities 0..1, 1, or *, and a direction that
is bidirectional.
In this example, the degree is unary (just the entity type PictureCategory is involved), the multiplicity is 0..1
and *, and the direction is, of course, bidirectional.
As is the case in this example, a self-referencing table often denotes a parent-child relationship, with each parent
having many children while each child has just one parent. Because the parent end of the relationship is 0..1 and
not 1, it is possible for a child to have no parent. This is just what you want to leverage in representing the root node;
that is, the one node that has no parent and is the top of the hierarchy.
Listing 2-7 shows how you can recursively enumerate the picture categories starting with the root node, which,
of course, is the only node that has no parent.
 
Search WWH ::




Custom Search