Tutorials Entity Framework Core Tutorial
Self Referencing Relationships in EF Core
Self Referencing Relationships in EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 49 of 100
Self Referencing Relationships in EF Core
Beginner ✓ → Intermediate ✓ → Advanced → Professional
Advanced · 3 — Production skills · ~6 min · Module 5: Relationships
What is this?
Self referencing relationships point an entity to others of the same type — Category with ParentCategoryId, Employee with ManagerId.
Why should you care?
ShopNest category tree (Electronics → Laptops → Gaming) uses self-reference instead of separate table per level.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
public class Category
{
public int Id { get; set; }
public string Name { get; set; } = "";
public int? ParentCategoryId { get; set; }
public Category? Parent { get; set; }
public ICollection<Category> Children { get; set; } = new List<Category>();
}
modelBuilder.Entity<Category>()
.HasOne(c => c.Parent)
.WithMany(c => c.Children)
.HasForeignKey(c => c.ParentCategoryId)
.OnDelete(DeleteBehavior.Restrict);
What happened?
- ParentCategoryId nullable FK allows root categories.
- HasOne/WithMany on same entity type configures hierarchy.
- Restrict prevents deleting parent with children.
Practice next
- Seed root and child categories.
- Query roots: Where(c => c.ParentCategoryId == null).
- Recursive CTE or client tree build for full hierarchy display.
- Load three levels with ThenInclude(c => c.Children).ThenInclude(c => c.Children).
- Add path column materialized for faster breadcrumb queries.
Remember
Same entity type for parent and child. Nullable FK marks root nodes. Restrict delete on hierarchies usually safest.
ShopNest category tree
Mega menu builds from self-referencing Category rows with ParentCategoryId.
Outcome: Unlimited depth aisles without schema change per level.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!