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.
A relationship has a principal (e.g. Customer) and a dependent that holds the foreign key (Order.CustomerId).
HasOne(o => o.Customer).WithMany(c => c.Orders).HasForeignKey(o => o.CustomerId).HasOne().WithOne(), and you must say which side holds the FK.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.
> "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 => o.Customer).WithMany(c => c.Orders).HasForeignKey(o => 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
Checks that the candidate can model relationships deliberately and understands the delete consequences.
Green flags
Red flags
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.
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.
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.
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.
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.
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.
Student/Course many-to-many with skip navigations and read the migration.EnrolledAt payload via UsingEntity<Enrolment> and compare.ClientSetNull and under Restrict.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]);
Restrict for business data; soft delete.HasForeignKey<T> on one-to-one. Why it is wrong: EF Core cannot pick the dependent and throws. Instead: name the dependent explicitly.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.BillingAddress and ShippingAddress). Why it is wrong: EF Core throws or pairs the wrong navigations. Instead: configure each relationship explicitly.Include graphs. Instead: add the navigation only on the side that needs it.NullReferenceException when adding. Instead: = [] (a C# 12 collection expression).NoAction blindly. Why it is wrong: the cleanup logic is lost. Instead: decide per path who owns deletion.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 |
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.
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.
Last updated 23 Nov 2026.