Entity Framework Core Interview Question #49

What is a self-referencing relationship in EF Core?

Relationships, Navigation Properties & Loading Data Junior Beginner

Quick Interview Answer

A self-referencing relationship occurs when an entity type relates to another entity of the same type.

Detailed Explanation

A self-referencing relationship occurs when an entity type relates to another entity of the same type.

Examples include an Employee with a Manager who is also an Employee, or a Category with a ParentCategory and child Categories.

These relationships should clearly define the foreign key, navigations, and delete behavior to avoid cycles or unintended cascading deletes.

Code Example

modelBuilder.Entity<Employee>()
    .HasOne(e => e.Manager)
    .WithMany(e => e.DirectReports)
    .HasForeignKey(e => e.ManagerId)
    .OnDelete(DeleteBehavior.Restrict);