Database Reference
In-Depth Information
2-5. Modeling a Self-Referencing Relationship with
a Code-First Approach
Problem
You have a table that references itself, and you want to model this as an entity with a self-referencing association using
a Code-First approach.
Solution
Let's say that you have a self-referencing table that's like the one shown in the database diagram in Figure 2-14 .
Figure 2-14. A self-referencing table
To create a model and import this table and the self-referencing relationship into the model, do the following:
1.
Create a new class that inherits from DbContext in your project.
Use the code in Listing 2-5 to create the PictureCategory POCO entity.
2.
Listing 2-5. Creating the PictureCategory POCO Entity
public class PictureCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CategoryId { get; private set; }
public string Name { get; set; }
public int? ParentCategoryId { get; private set; }
[ForeignKey("ParentCategoryId")]
public PictureCategory ParentCategory { get; set; }
public List<PictureCategory> Subcategories { get; set; }
public PictureCategory()
{
Subcategories = new List<PictureCategory>();
}
}
 
Search WWH ::




Custom Search