skip to content

Cardinality & Cascade Delete

Configuring EF Core relationships: one-to-many, one-to-one and many-to-many, required versus optional foreign keys, and cascade delete. Interviewers ask what deleting a parent does to its children.

part ofEntity Framework Coreread it →
on this pageshow

explore

questions

5

In EF Core 10, how do you configure a one-to-many relationship with HasOne, WithMany and HasForeignKey, and what makes it required or optional?

level: juniorimportance: must knowfreq 72%

answer

  1. principal key, dependent foreign key
  2. the chain can start from either end
  3. int versus int? on the FK
  4. IsRequired() on the relationship builder
  5. HasForeignKey<T> names the one-to-one dependent

basics

~10 s

In OnModelCreating, call HasOne(c => c.Department).WithMany(d => d.Courses).HasForeignKey(c => c.DepartmentId) on the dependent. A non-nullable foreign key makes the relationship required; a nullable one such as int? makes it optional.

solid answer

~40 s

A one-to-many relationship has a **principal** (`Department`) whose key is referenced by a **foreign key** on the **dependent** (`Course.DepartmentId`). EF Core discovers it by convention from the navigations and the `DepartmentId` name, but you can state it in `OnModelCreating` from either end: `modelBuilder.Entity<Course>().HasOne(c => c.Department).WithMany(d => d.Courses).HasForeignKey(c => c.DepartmentId)`, or `Entity<Department>().HasMany(d => d.Courses).WithOne(c => c.Department)` - one chain describes one relationship. Whether it is **required** follows the foreign key: `int DepartmentId` makes it required, and required relationships cascade deletes by default; `int? DepartmentId` makes it optional. `IsRequired()` states it explicitly, and with nullable reference types a non-nullable navigation makes a shadow foreign key required. Required means every course must point at a department - not that every department has courses.

code

csharp · 22 lines
csharp
public class Department
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List<Course> Courses { get; } = [];
}

public class Course
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public int DepartmentId { get; set; }            // non-nullable: required
    public Department Department { get; set; } = null!;
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Course>()
        .HasOne(c => c.Department)
        .WithMany(d => d.Courses)
        .HasForeignKey(c => c.DepartmentId);
}

go deeper

for a junior

Recall the four parts - principal, dependent, foreign key, navigations - and write the HasOne / WithMany / HasForeignKey chain from memory.

for a middle

Explain how the foreign key's nullability decides required versus optional and which delete behaviour each gets by default, including shadow keys under nullable reference types.

for a senior

Show when conventions are not enough - ambiguous pairs of relationships between the same types, legacy column names - and how a one-to-one dependent is chosen and indexed.

for a principal

Frame required-ness as a domain invariant the schema enforces on dependents only, and decide where principal-side rules such as 'a department has courses' must live instead.

## The parts of a relationship EF Core describes every relationship between entity types with the same few parts. In a school system where each course belongs to one department: - **Principal** - the entity that is referenced, here `Department`. Its primary key (`Department.Id`) is the **principal key**. - **Dependent** - the entity that holds the reference, here `Course`. It carries the **foreign key** property `Course.DepartmentId`, mapped to a foreign key column and constraint. - **Reference navigation** - a property holding one related entity, such as `Course.Department`. - **Collection navigation** - a property holding many related entities, such as `Department.Courses`. - Both navigations are optional in the model: a relationship can have one, both or neither, but it always has a foreign key (a **shadow** property if the class declares none). A relationship with navigations on both sides is **bidirectional**. EF Core pairs the two navigations into one relationship when the types and names line up. ## Configuring it with the fluent API Conventions find `Department.Courses`, `Course.Department` and `Course.DepartmentId` without any code. Fluent configuration in `OnModelCreating` (or an `IEntityTypeConfiguration<T>` class) is needed when names do not follow the convention, when two relationships between the same pair of types make the pairing ambiguous, or when you want to change a default such as the delete behaviour. 1. Start from the entity that owns one end: `modelBuilder.Entity<Course>()`. 2. `HasOne(c => c.Department)` names the reference navigation on that entity. 3. `WithMany(d => d.Courses)` names the inverse collection; `WithMany()` with no argument means there is none. 4. `HasForeignKey(c => c.DepartmentId)` names the foreign key property on the dependent. 5. Optionally `IsRequired()` and `OnDelete(...)` refine it. The same relationship can be configured from the principal instead: `modelBuilder.Entity<Department>().HasMany(d => d.Courses).WithOne(c => c.Department).HasForeignKey(c => c.DepartmentId)`. Both chains build the same single relationship; you write one of them, not both. ## Required versus optional | Model | Relationship | Default delete behaviour | |---|---|---| | `int DepartmentId` | required | `Cascade` | | `int? DepartmentId` | optional | `ClientSetNull` | | no FK property, nullable reference types on, `Department Department` | required (shadow `int` key) | `Cascade` | | no FK property, `Department? Department` | optional (shadow `int?` key) | `ClientSetNull` | | `int? DepartmentId` plus `IsRequired()` | required | `Cascade` | Two details matter in interviews: - **Nullability decides.** A non-nullable foreign key cannot hold "no department", so the relationship is required. With nullable reference types, the navigation from dependent to principal must be nullable whenever the foreign key is nullable. - **`IsRequired(false)` cannot loosen an `int` key.** EF Core refuses to mark a property of a non-nullable CLR type as optional; change the type to `int?` instead. ## Relationships with one navigation Not every relationship needs both navigations. If departments never list their courses in code, drop `Department.Courses` and write `HasOne(c => c.Department).WithMany()`: the empty `WithMany()` says the principal has no collection. The reverse - a collection on `Department` and no reference on `Course` - is configured as `HasMany(d => d.Courses).WithOne()`. Either way the foreign key column, the required/optional rule and the delete behaviour are exactly the same; only what C# code can walk changes. ## What required does and does not promise A required relationship means every **dependent** must be related to some principal: a course row cannot exist without a department. It does **not** mean a department must have courses - there is no way in the EF Core model, and no standard way in a relational database, to force a principal to have dependents. That rule belongs in application code. ## One-to-one: telling EF Core which side is the dependent In one-to-many, the side with the collection is always the principal. In one-to-one both ends are references, so EF Core needs to be told where the foreign key lives. For a `Student` with one `StudentCard`: - `modelBuilder.Entity<Student>().HasOne(s => s.Card).WithOne(c => c.Student).HasForeignKey<StudentCard>(c => c.StudentId)`. - The type argument of `HasForeignKey<StudentCard>` names the **dependent**. - EF Core puts a **unique** index on a one-to-one foreign key, so a student cannot get two cards. - When no foreign key is found or configured, EF Core can fail with "The dependent side could not be determined for the one-to-one relationship". ## Common mistakes - Expecting assignment to write anything: setting `course.Department` changes memory only; EF Core writes the foreign key on `SaveChanges`. - Configuring two relationships by accident, for example `WithMany()` with no argument while `Department.Courses` exists, which can leave the collection to form a second relationship by convention. - Reading "required" as "the principal always has children".

  • How does a one-to-one between Student and StudentCard differ in configuration?
    Both ends are references, so the dependent is not implied. Write `HasOne(s => s.Card).WithOne(c => c.Student).HasForeignKey<StudentCard>(c => c.StudentId)`: the type argument names the dependent that holds the key. EF Core gives that foreign key a unique index, and when no key is found or configured it can fail because the dependent side could not be determined.
  • When do you need fluent configuration if conventions already find the relationship?
    When names do not follow the convention (say `OwningDepartmentId`), when two relationships connect the same types - a course with both `Department` and `CrossListedDepartment` - so EF Core cannot pair navigations, or when you want a non-default delete behaviour through `OnDelete`. Otherwise the explicit chain only restates what conventions build.

  • Setting course.Department immediately writes DepartmentId to the database
  • A required relationship guarantees every department has at least one course
  • You must configure HasMany on the principal and HasOne on the dependent for one relationship
  • In HasForeignKey<StudentCard>, the type argument names the principal
  • An int? foreign key still cascades deletes by default
  • IsRequired(false) makes an int foreign key optional
open as a page

In EF Core 10, what happens to a course's enrolments when the course is deleted, and how do OnDelete and DeleteBehavior change that?

level: middleimportance: must knowfreq 66%

basics

~20 s

With the default required relationship (Cascade), EF Core deletes tracked enrolments itself and the database's ON DELETE CASCADE removes untracked ones. OnDelete(DeleteBehavior...) changes both what EF Core does to tracked rows and the constraint migrations create.

open as a page

In EF Core 10, when is a Student-Course many-to-many mapped with skip navigations alone, and when does it need an Enrollment join entity through UsingEntity?

level: middleimportance: should knowfreq 55%

basics

~20 s

With only Student.Courses and Course.Students, EF Core creates a hidden shared-type join entity and a CourseStudent table. Once the link carries data such as an enrolment date or grade, map an Enrollment class with UsingEntity<Enrollment>().

open as a page

In EF Core 10, why does removing an enrolment from course.Enrollments delete its row on SaveChanges, and how do you move it to another course instead?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The Course-Enrollment relationship is required and cascades, so an enrolment removed from the collection becomes an orphan that EF Core marks Deleted. Move it by setting enrollment.Course or CourseId to the new course, not by removing it first.

open as a page

Deleting an EF Core 10 student who mentors other students throws DbUpdateException although Student.MentorId is nullable - why, and how do you fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The self-referencing Mentor relationship is optional, so its default ClientSetNull nulls MentorId only on tracked mentees; the constraint has no ON DELETE action, so unloaded mentees still reference the row. Load the mentees, or configure OnDelete(DeleteBehavior.SetNull).

open as a page