📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you model relationships in EF Core? Explain one-to-many, one-to-one and many-to-many with skip navigations, required versus optional relationships, and the cascade delete behaviours you can choose.

Covers EF Core relationship mapping: principal and dependent, foreign keys and navigations, one-to-many, one-to-one, many-to-many with skip navigations and payload join entities, required versus optional, and DeleteBehavior options.

Intermediate Theory Intermediate cascade-delete ef-core fluent-api foreign-keys many-to-many relationships

🎯 Key points

  • Principal vs dependent; the FK lives on the dependent
  • HasOne/WithMany/HasForeignKey; one-to-one needs HasForeignKey<T> to name the dependent
  • Many-to-many via skip navigations; explicit join entity (UsingEntity<T>) when it has a payload
  • Required = non-nullable FK → Cascade by default; optional → ClientSetNull
  • DeleteBehavior: Cascade, Restrict, NoAction, SetNull, ClientSetNull, ClientCascade
  • SQL Server rejects multiple cascade paths (error 1785) → Restrict/NoAction on one path
  • EF Core creates an index on every FK by convention (unique for one-to-one)

⏱ 30-second answer

A relationship has a principal (e.g. Customer) and a dependent that holds the foreign key (Order.CustomerId).

  • One-to-many: HasOne(o => o.Customer).WithMany(c => c.Orders).HasForeignKey(o => o.CustomerId).
  • One-to-one: HasOne().WithOne(), and you must say which side holds the FK.
  • Many-to-many: two collection skip navigations; EF Core creates the join table. Use an explicit join entity when the link has data (e.g. EnrolledAt).

Required relationships (non-nullable FK) default to cascade delete; optional ones default to ClientSetNull. The trade-off: cascades are convenient but can delete far more than intended and SQL Server refuses multiple cascade paths, so I default to Restrict for anything important.

🗣 Full answer (senior)

How I would answer this in an interview

> "Every relationship in EF Core has a principal and a dependent, and the dependent holds the foreign key. In a one-to-many, Order is the dependent with CustomerId, and I configure it with HasOne(o =&gt; o.Customer).WithMany(c =&gt; c.Orders).HasForeignKey(o =&gt; o.CustomerId). Conventions often discover this on their own, but I write it explicitly for anything non-trivial. One-to-one is the same idea except EF Core can't guess which side is dependent, so `HasForeignKey

🔍 What the interviewer is checking

Checks that the candidate can model relationships deliberately and understands the delete consequences.

Green flags

  • Names principal and dependent correctly
  • Knows when to use an explicit join entity
  • Discusses cascade risk and multiple cascade paths
  • Differentiates ClientSetNull from SetNull

Red flags

  • Relies on conventions without knowing what they produced
  • Thinks cascade delete is always fine

📚 Learn in depth

1. Principal, dependent and keys

Customer (principal)          Order (dependent)
┌──────────┐                  ┌──────────────────┐
│ Id (PK)  │◄──── FK ─────────│ CustomerId (FK)  │
└──────────┘                  └──────────────────┘

The FK references a principal key (usually the PK, but an alternate key works via HasPrincipalKey). If you omit the FK property, EF Core creates a shadow FK named CustomerId.

2. How EF Core discovers relationships

The relationship discovery convention pairs navigations by type: a reference navigation to Customer plus a collection of Order on Customer becomes one relationship. Ambiguity (two navigations to the same type) needs explicit configuration.

3. Required versus optional

Required = FK not nullable. The dependent cannot exist without its principal. Optional = nullable FK. NRT affects navigation nullability too: Customer Customer (non-nullable) suggests required.

4. Cascade in SQL Server

SQL Server refuses a schema where a delete could reach a table along two cascade paths (error 1785). Example: Company → Employee and Company → Project → Assignment → Employee. Fix by setting one path to Restrict or NoAction.

5. Fix-up

When you set order.Customer = customer, EF Core updates order.CustomerId and adds the order to customer.Orders during DetectChanges. This relationship fix-up happens for tracked entities only.

6. Join entities

Skip navigations use a shared-type entity Dictionary<string, object> by default. UsingEntity<Enrolment>() lets you supply your own class with payload columns while keeping the skip navigations.

Try it yourself

  1. Model Student/Course many-to-many with skip navigations and read the migration.
  2. Add an EnrolledAt payload via UsingEntity<Enrolment> and compare.
  3. Create two cascade paths and see the SQL Server 1785 error when applying the migration.
  4. Delete a principal with tracked dependents under ClientSetNull and under Restrict.

💻 Code

Explicit relationship configuration with safe delete behaviour.

namespace School.Infrastructure;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public sealed class Customer
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public List<Order> Orders { get; } = [];
    public CustomerProfile? Profile { get; set; }
}

public sealed class Order
{
    public int Id { get; set; }
    public int CustomerId { get; set; }          // non-nullable → required
    public Customer Customer { get; set; } = null!;
}

public sealed class CustomerProfile
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public string? Bio { get; set; }
}

public sealed class Student
{
    public int Id { get; set; }
    public List<Course> Courses { get; } = [];
}

public sealed class Course
{
    public int Id { get; set; }
    public List<Student> Students { get; } = [];
}

public sealed class Enrolment
{
    public int StudentId { get; set; }
    public int CourseId { get; set; }
    public DateTimeOffset EnrolledAt { get; set; }   // payload
}

public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> b) =>
        b.HasOne(o => o.Customer)
         .WithMany(c => c.Orders)
         .HasForeignKey(o => o.CustomerId)
         .OnDelete(DeleteBehavior.Restrict);         // deleting a customer must be a decision
}

public sealed class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
    public void Configure(EntityTypeBuilder<Customer> b) =>
        b.HasOne(c => c.Profile)
         .WithOne()
         .HasForeignKey<CustomerProfile>(p => p.CustomerId); // one-to-one: say who holds the FK
}

public sealed class StudentConfiguration : IEntityTypeConfiguration<Student>
{
    public void Configure(EntityTypeBuilder<Student> b) =>
        b.HasMany(s => s.Courses)
         .WithMany(c => c.Students)
         .UsingEntity<Enrolment>(
             r => r.HasOne<Course>().WithMany().HasForeignKey(e => e.CourseId),
             l => l.HasOne<Student>().WithMany().HasForeignKey(e => e.StudentId),
             j => j.Property(e => e.EnrolledAt).HasDefaultValueSql("SYSUTCDATETIME()"));
}
ALTER TABLE [Orders] ADD CONSTRAINT [FK_Orders_Customers_CustomerId]
    FOREIGN KEY ([CustomerId]) REFERENCES [Customers] ([Id]);   -- NO ACTION (Restrict)
CREATE UNIQUE INDEX [IX_CustomerProfile_CustomerId] ON [CustomerProfile] ([CustomerId]);

⚠ Common mistakes

  • Mistake: Accepting cascade delete on every required relationship. Why it is wrong: one delete can remove thousands of rows and lock tables. Instead: Restrict for business data; soft delete.
  • Mistake: Forgetting HasForeignKey<T> on one-to-one. Why it is wrong: EF Core cannot pick the dependent and throws. Instead: name the dependent explicitly.
  • Mistake: Using skip navigations when the link has data. Why it is wrong: there is nowhere to store the payload. Instead: an explicit join entity.
  • Mistake: Assuming ClientSetNull changes the database. Why it is wrong: the FK is NO ACTION; untracked dependents block the delete. Instead: use SetNull if the database should null it.
  • Mistake: Making a FK nullable "just in case". Why it is wrong: the relationship becomes optional, orphans become possible and the default delete behaviour changes. Instead: make the FK nullability match the business rule.
  • Mistake: Letting conventions pair navigations when an entity has two references to the same type (e.g. BillingAddress and ShippingAddress). Why it is wrong: EF Core throws or pairs the wrong navigations. Instead: configure each relationship explicitly.
  • Mistake: Adding navigations on both sides everywhere. Why it is wrong: it couples aggregates and invites huge Include graphs. Instead: add the navigation only on the side that needs it.
  • Mistake: Not initialising collection navigations. Why it is wrong: NullReferenceException when adding. Instead: = [] (a C# 12 collection expression).
  • Mistake: Ignoring error 1785 by switching everything to NoAction blindly. Why it is wrong: the cleanup logic is lost. Instead: decide per path who owns deletion.

🏛 Senior insight: trade-offs

Relationship configuration is where data-loss bugs hide. Cascades encode a business rule ("an order line cannot exist without its order") and should only exist where that rule is true and the fan-out is small. Everything else should require an explicit delete or a soft delete, which also helps with Privacy Act retention and audit requirements.

Performance matters too. A database cascade runs inside the deleting statement's transaction: deleting one principal with [50,000] dependents takes exclusive locks on every affected row, can escalate to a table lock (SQL Server escalates at about 5,000 locks on one object) and grows the transaction log in one burst. ClientCascade is worse: EF Core must load every dependent into the change tracker first. For large fan-outs, delete in batches with ExecuteDeleteAsync (e.g. 1,000 rows per statement) inside a background job. Also check that every FK has an index (EF Core adds one by convention, but hand-written or scaffolded schemas may not); without it each cascade or Restrict check scans the child table.

Delete behaviour When it fits Cost When not to
Cascade Composition with small fan-out (order → lines) Hidden mass deletes, long locks Aggregates referenced by others
Restrict / NoAction Business entities Explicit cleanup code Pure owned children
SetNull Optional references ("assigned agent") Orphaned rows to handle Required relationships
Batched ExecuteDelete job Large fan-outs, retention purges A job to run and monitor Small, interactive deletes

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions cascade delete. Why: Checks practical knowledge of SQL Server cascade rules.
    How to answer

    It is SQL Server error 1785: SQL Server refuses a foreign key with ON DELETE CASCADE when the table can already be reached by another cascade path, or the cascade would form a cycle. EF Core makes required relationships cascade by default, so a model like Company → Projects → Tasks plus Company → Employees → Tasks triggers it. Fix it by choosing which path really owns the delete and setting the other relationship to DeleteBehavior.Restrict or DeleteBehavior.NoAction (both emit ON DELETE NO ACTION on SQL Server; ClientCascade is an option if EF Core should delete loaded dependents itself). Then delete the dependents explicitly in the use case, often with ExecuteDelete, or switch to soft delete: an IsDeleted flag or DeletedAt column plus a global query filter, so nothing is physically removed. Wide cascades also lock many rows in one transaction, so avoiding them helps performance.

  2. When: Candidate mentions skip navigations. Why: Checks modelling judgement.
    How to answer

    Use skip navigations alone (Student.Courses / Course.Students with a hidden shared-type join table) when the link is just a pair of keys. Switch to an explicit join entity such as Enrolment when the link has payload (enrolment date, role, quantity, price at the time), needs its own identity or audit trail (who linked it, when, soft delete), or is queried or paged on its own. You can keep the convenience of skip navigations and a join class by mapping it with HasMany(...).WithMany(...).UsingEntity<Enrolment>(); or drop the skip navigations and model two plain one-to-many relationships. Performance is similar: both generate the same join through the link table; the explicit entity mainly lets you filter on payload in SQL, project it, and index it, instead of loading links you then discard.

↩ Usually asked after

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me