Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 41 ยท Relationships and Loading

Fluent API Relationship Configuration

Configure EF Core relationships explicitly with HasOne, HasMany, WithOne, HasForeignKey, HasPrincipalKey, OnDelete, UsingEntity, self-references and owned types, plus a runnable builder stand-in.

Conventions get you far, but real models always hit cases they cannot guess: a foreign key with an unusual name, a relationship that must restrict deletes, a self-referencing tree, two relationships between the same pair of types. The Fluent API is EF Core's code-based configuration, written inside OnModelCreating. It is the most powerful of the three ways to configure a model (conventions, data annotations, Fluent API) and it always wins when they disagree.

As elsewhere in this chapter, the EF Core code is read-only; the runnable block is a tiny stand-in that mimics the shape of a fluent builder.

The pattern: HasX, WithY

Every relationship is configured from one end with a Has... call that names the navigation on that end, followed by a With... call that names the navigation on the other end:

C#
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>()
        .HasOne(p => p.Blog)            // Post has one Blog
        .WithMany(b => b.Posts)         // Blog has many Posts
        .HasForeignKey(p => p.BlogId)   // using this property
        .IsRequired()                   // NOT NULL
        .OnDelete(DeleteBehavior.Cascade);
}
Starting call Followed by Relationship
HasOne WithMany One-to-many (this is the dependent)
HasMany WithOne One-to-many (this is the principal)
HasOne WithOne One-to-one (add HasForeignKey<T>)
HasMany WithMany Many-to-many

Calling either end gives the same model. Pick the one that reads best.

Foreign keys that are not named by convention

If the column is called OwnerCode and it references a non-primary unique column, use HasForeignKey plus HasPrincipalKey:

C#
modelBuilder.Entity<Pet>()
    .HasOne(p => p.Owner)
    .WithMany(o => o.Pets)
    .HasForeignKey(p => p.OwnerCode)
    .HasPrincipalKey(o => o.Code);      // alternate key; EF Core adds a unique constraint

If you do not want a foreign key property in your class at all, EF Core can create a shadow property: HasForeignKey("OwnerId") with a string name creates a column without a CLR property. It keeps your domain classes clean, but you cannot filter on it with a plain property access (use EF.Property<int>(p, "OwnerId")).

Delete behavior

OnDelete sets what happens to dependents:

C#
.OnDelete(DeleteBehavior.Restrict)     // refuse to delete a Blog that still has Posts
.OnDelete(DeleteBehavior.SetNull)      // needs a nullable foreign key
.OnDelete(DeleteBehavior.Cascade)      // delete the Posts too

Be deliberate. Cascade on every relationship can create multiple cascade paths that SQL Server refuses to create, and it also means one careless Remove can delete a lot of data. A good default for important business data is Restrict, with explicit cleanup code.

Self-referencing relationships

A category tree, an employee-manager hierarchy and threaded comments all point at their own type:

C#
public class Category
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public int? ParentId { get; set; }                 // nullable: the root has no parent
    public Category? Parent { get; set; }
    public List<Category> Children { get; } = new();
}

modelBuilder.Entity<Category>()
    .HasOne(c => c.Parent)
    .WithMany(c => c.Children)
    .HasForeignKey(c => c.ParentId)
    .OnDelete(DeleteBehavior.Restrict);   // cascades on self-references are usually refused by SQL Server

Two relationships between the same types

When Flight has both a Departure and an Arrival airport, convention cannot pair navigations, so you name each pair:

C#
modelBuilder.Entity<Flight>().HasOne(f => f.From).WithMany(a => a.Departures).HasForeignKey(f => f.FromId);
modelBuilder.Entity<Flight>().HasOne(f => f.To).WithMany(a => a.Arrivals).HasForeignKey(f => f.ToId);

If you also use [InverseProperty] annotations you get the same result in the class itself.

Many-to-many with a configured join entity

UsingEntity lets you customize the join table, give it a payload and keep skip navigations:

C#
modelBuilder.Entity<Student>()
    .HasMany(s => s.Courses)
    .WithMany(c => c.Students)
    .UsingEntity<Enrollment>(
        right => right.HasOne(e => e.Course).WithMany(c => c.Enrollments).HasForeignKey(e => e.CourseId),
        left  => left.HasOne(e => e.Student).WithMany(s => s.Enrollments).HasForeignKey(e => e.StudentId),
        join  => join.HasKey(e => new { e.StudentId, e.CourseId }));

Owned types: a relationship that is not an entity

Value-like data that belongs to exactly one owner, such as an Address, can be an owned type. It has no key of its own and no DbSet; by default it lives in the owner's table:

C#
modelBuilder.Entity<Customer>().OwnsOne(c => c.ShippingAddress);
// columns: ShippingAddress_Street, ShippingAddress_City, ...

In EF Core 8 and later you can also model such groups as complex types (ComplexProperty), which have value semantics and need no identity.

Where to put configuration

Large models become unreadable if every rule is in one method. Keep one configuration class per entity:

C#
public class PostConfiguration : IEntityTypeConfiguration<Post>
{
    public void Configure(EntityTypeBuilder<Post> builder)
    {
        builder.HasOne(p => p.Blog).WithMany(b => b.Posts).HasForeignKey(p => p.BlogId);
    }
}

// in OnModelCreating
modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);

A stand-in for the builder idea

Fluent APIs are ordinary method chains that return this. This small model builder records a relationship and checks the same kind of rule EF Core checks when the model is built (a required relationship cannot use SetNull):

C# Stand-in: a fluent relationship builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice how each call returns the builder, so the chain reads like a sentence. That is all the Fluent API is.

Seeing the model

You can inspect what EF Core decided:

C#
Console.WriteLine(db.Model.ToDebugString());   // keys, foreign keys, indexes, delete behaviors

and the migration you generate (Migrations) shows the foreign keys and ON DELETE clauses in SQL form, which is the quickest way to confirm your configuration.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which configuration source wins when conventions, data annotations and the Fluent API disagree?

    The Fluent API has the highest precedence.
  2. 2. A foreign key must reference a unique non-primary-key column. Which call do you add?

    HasPrincipalKey names the (alternate) key on the principal that the foreign key targets.
  3. 3. Why is DeleteBehavior.Restrict a safe default for important data?

    Restrict prevents accidental mass deletion; you handle cleanup explicitly.
  4. 4. What is an owned type?

    Owned types (like an Address) are part of their owner and by default share its table.

Summary

  • Relationships are configured with HasOne/HasMany plus WithMany/WithOne, then HasForeignKey, IsRequired and OnDelete.
  • HasPrincipalKey targets an alternate key; shadow properties hide the foreign key from your class.
  • Prefer Restrict for valuable data; watch out for multiple cascade paths.
  • Self-references need a nullable parent key; two relationships between the same types need explicit pairs.
  • UsingEntity customizes join tables; OwnsOne and complex types model value-like data.
  • Split configuration into IEntityTypeConfiguration<T> classes.

Next: Eager loading with Include