Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 41 ยท Relationships and Loading

One-to-Many Relationships

Learn how EF Core models one-to-many relationships with foreign keys, navigation properties, required and optional dependents, conventions and cascade delete, with runnable C# stand-ins.

Almost every real database has tables that point at each other: a blog has many posts, a customer has many orders, a department has many employees. In a relational database this is done with a foreign key column. In Entity Framework Core (EF Core) you describe the same thing with plain C# properties, and EF Core works out the SQL. The most common shape is the one-to-many relationship, so we start here.

The real EF Core needs a database provider, NuGet packages and the dotnet ef tools, none of which can run in this site's sandbox. So every EF Core snippet in this chapter is read-only (the output is shown only where it is certain), and every runnable block is a small stand-in written in plain C# that imitates the idea being explained (for example, how a foreign key is filled in). Stand-ins are labelled as such. They teach the concept; they are not EF Core.

The vocabulary: principal and dependent

Every relationship has two ends.

  • The principal entity is the "one" side. It owns the key that the other side refers to (Blog).
  • The dependent entity is the "many" side. It holds the foreign key (Post.BlogId).
erDiagram
    BLOG ||--o{ POST : "has many"
    BLOG {
        int Id PK
        string Title
    }
    POST {
        int Id PK
        int BlogId FK
        string Heading
    }

One blog row can be referenced by many post rows; each post row points back with BlogId.

Modeling it by convention

EF Core finds relationships by convention. If you write a navigation property on one side, a foreign-key property and a navigation on the other side, nothing else is needed:

C#
public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; } = "";

    // Collection navigation: the "many" side
    public List<Post> Posts { get; set; } = new();
}

public class Post
{
    public int Id { get; set; }
    public string Heading { get; set; } = "";

    // Foreign key property
    public int BlogId { get; set; }

    // Reference navigation back to the principal
    public Blog Blog { get; set; } = null!;
}

The convention is: a property named <NavigationName><PrincipalKeyName> (here BlogId), or <PrincipalTypeName><PrincipalKeyName>, is picked up as the foreign key. You can also have only one of the navigations (a one-directional relationship), or only the foreign key property. Having both navigations is the most convenient because you can walk the object graph in both directions.

Required or optional?

Whether the dependent can exist without a principal is decided by the nullability of the foreign key.

C#
public class Post
{
    public int Id { get; set; }
    public int BlogId { get; set; }          // int: required, a post must have a blog
    public Blog Blog { get; set; } = null!;
}

public class Ticket
{
    public int Id { get; set; }
    public int? AssigneeId { get; set; }     // int?: optional, may be unassigned
    public Person? Assignee { get; set; }
}

A non-nullable int BlogId becomes a NOT NULL column and the relationship is required. A nullable int? makes the column nullable. With nullable reference types enabled, Blog Blog (non-nullable) also marks the relationship required, while Blog? Blog marks it optional. The = null! initializer tells the compiler "EF Core will fill this in"; it is not a real null you should rely on.

What EF Core does for you: fix-up

When you add a Post to blog.Posts, EF Core sets post.Blog and post.BlogId for you when it tracks the entities. This is called relationship fix-up. You can build a graph in memory and save it in one call:

C#
var blog = new Blog { Title = "Cooking" };
blog.Posts.Add(new Post { Heading = "Soup" });
blog.Posts.Add(new Post { Heading = "Bread" });

db.Blogs.Add(blog);      // EF Core also tracks the two posts
await db.SaveChangesAsync();
// INSERT INTO Blogs ...; then two INSERT INTO Posts with the new blog Id

EF Core inserts the principal first, reads the generated key, and then writes it into each dependent's foreign key. You never copy Id values by hand.

Here is a runnable stand-in for fix-up: a tiny Add method that behaves like the tracker when it discovers a new post on a blog.

C# Stand-in: relationship fix-up

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.

Deleting: cascade behavior

What should happen to posts when their blog is deleted? A required relationship cascades by default: deleting the principal deletes its dependents. An optional one defaults to ClientSetNull: tracked dependents get their foreign key set to NULL and untracked ones are left to the database, which may reject the delete.

You choose this with OnDelete in the Fluent API (more in Fluent API relationship configuration):

Behavior Effect on dependents when the principal is deleted
Cascade Dependents are deleted too
SetNull Foreign key becomes NULL (needs an optional relationship)
Restrict / NoAction Delete is refused while dependents exist
ClientSetNull EF Core nulls tracked dependents; the database restricts
ClientCascade EF Core deletes tracked dependents; the database restricts

Try the behaviors on a stand-in table:

C# Stand-in: delete behaviors

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.

Common mistakes

  • Forgetting to initialize the collection. public List<Post> Posts { get; set; } that is null throws when you call Add. Initialize it (= new()) or use a backing field.
  • Setting only the navigation or only the foreign key inconsistently. If both are set and disagree, the navigation usually wins at SaveChanges. Set one, not both.
  • Assuming a collection is loaded. A blog.Posts that you did not load is simply empty; it does not mean the blog has no posts. See eager loading.
  • Exposing the collection as List<T> setter. Prefer ICollection<Post> or a get-only property so callers cannot replace the collection that EF Core tracks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which entity holds the foreign key in a one-to-many relationship?

    The dependent (many) side stores the foreign key column that points to the principal's key.
  2. 2. What makes a one-to-many relationship optional?

    A nullable foreign key (or nullable reference navigation) means a dependent can exist without a principal.
  3. 3. What is relationship fix-up?

    Fix-up means EF Core keeps navigation properties and foreign key values in step for tracked entities.
  4. 4. A required relationship uses default delete behavior. What happens to dependents when the principal is deleted?

    Required relationships cascade by default, so dependents are deleted along with the principal.

Summary

  • One-to-many means one principal row with many dependent rows that hold a foreign key.
  • By convention a collection navigation, a reference navigation and a BlogId-style property are enough.
  • A nullable foreign key makes the relationship optional; a non-nullable one makes it required.
  • EF Core fixes up navigations and keys for tracked entities and inserts the principal first.
  • OnDelete controls what happens to dependents; required relationships cascade by default.

Next: One-to-one and many-to-many relationships