Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 41 ยท Relationships and Loading

One-to-One and Many-to-Many Relationships

Model one-to-one and many-to-many relationships in EF Core: unique foreign keys, skip navigations, explicit join entities with payload data, with read-only EF code and runnable stand-ins.

One-to-many covers most of what you will model, but two other shapes appear often. A one-to-one relationship links exactly one row to at most one row on the other side (a user and their profile). A many-to-many relationship links many rows to many rows (students and courses, posts and tags). Relational databases cannot store a many-to-many link in a single column, so a third table, the join table, sits in the middle. EF Core can hide that table or let you model it as a full entity.

All EF Core snippets here are read-only; the runnable blocks are plain C# stand-ins for the ideas.

One-to-one

In a one-to-one relationship one side is still the dependent and holds the foreign key. The difference from one-to-many is that the foreign key is unique, so two dependents cannot point at the same principal.

C#
public class User
{
    public int Id { get; set; }
    public string Email { get; set; } = "";
    public UserProfile? Profile { get; set; }          // reference navigation, not a collection
}

public class UserProfile
{
    public int Id { get; set; }
    public string DisplayName { get; set; } = "";

    public int UserId { get; set; }                    // foreign key
    public User User { get; set; } = null!;
}

With two reference navigations EF Core cannot guess which side is the dependent, so it needs help when the foreign key name does not make it obvious. In this example UserId makes UserProfile the dependent by convention. When in doubt, say it explicitly:

C#
modelBuilder.Entity<User>()
    .HasOne(u => u.Profile)
    .WithOne(p => p.User)
    .HasForeignKey<UserProfile>(p => p.UserId);

EF Core creates a unique index on UserProfile.UserId, which is what turns the relationship into one-to-one at the database level.

A variation is table splitting or sharing the primary key: the dependent's primary key is the foreign key (UserProfile.Id equals User.Id). That saves a column and guarantees uniqueness without a second index.

Here is a stand-in that enforces the same rule, so you can see what the unique index protects you from:

C# Stand-in: a unique foreign key

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.

Many-to-many with skip navigations

Since EF Core 5 you can model many-to-many without writing the join class. Each entity has a collection of the other, and EF Core creates the join table behind the scenes:

C#
public class Post
{
    public int Id { get; set; }
    public string Heading { get; set; } = "";
    public List<Tag> Tags { get; } = new();      // skip navigation
}

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List<Post> Posts { get; } = new();    // skip navigation
}

The database gets a PostTag table with PostsId and TagsId columns whose combination is the primary key. You work only with the two collections:

C#
var post = await db.Posts.Include(p => p.Tags).FirstAsync(p => p.Id == 1);
post.Tags.Add(await db.Tags.FirstAsync(t => t.Name == "csharp"));
await db.SaveChangesAsync();      // inserts one row into PostTag
erDiagram
    POST ||--o{ POSTTAG : ""
    TAG ||--o{ POSTTAG : ""
    POSTTAG {
        int PostsId PK
        int TagsId PK
    }

The join table holds one row per link; a pair can appear only once.

Many-to-many with an explicit join entity

The hidden join table is great until you need extra data on the link: when a student enrolled, which grade they got, in which order a tag is shown. Then the join becomes a real entity with two one-to-many relationships:

C#
public class Enrollment
{
    public int StudentId { get; set; }
    public Student Student { get; set; } = null!;

    public int CourseId { get; set; }
    public Course Course { get; set; } = null!;

    public DateOnly EnrolledOn { get; set; }
    public int? Grade { get; set; }
}

// Composite primary key (Fluent API only)
modelBuilder.Entity<Enrollment>().HasKey(e => new { e.StudentId, e.CourseId });

You can still keep skip navigations and the join entity together by configuring UsingEntity (see Fluent API relationship configuration); that way you get student.Courses for reading and student.Enrollments for payload.

Choose by this rule: if the link has no data of its own, use skip navigations; if it will ever need data, start with the join entity because changing later means a migration.

C# Stand-in: a join entity with payload

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.

Which side is the principal?

Relationship Foreign key lives in Key detail
One-to-many The "many" side Foreign key can repeat
One-to-one The dependent side Foreign key has a unique index
Many-to-many A join table Composite key of both foreign keys

Common mistakes

  • Not saying which side is dependent in a one-to-one. EF Core throws at model-building time asking you to call HasForeignKey<T>.
  • Using skip navigations and later needing payload. Adding a CreatedAt to the link later means switching to an explicit join entity and a data migration.
  • Forgetting Include for both ends. Reading post.Tags without loading them gives an empty list. See eager loading.
  • Adding a duplicate link. The composite primary key makes the second insert fail at SaveChanges; check first or catch the exception.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes a relationship one-to-one at the database level?

    The dependent's foreign key has a unique index, so no two dependents can reference the same principal.
  2. 2. Which approach lets you store the enrollment date on a student-course link?

    Payload data needs a real entity class for the join table.
  3. 3. What is the usual primary key of a join table?

    The pair (StudentId, CourseId) is unique and identifies a link.
  4. 4. Why might EF Core ask you to call HasForeignKey<T> on a one-to-one?

    With a reference navigation on each side and no clear key name, EF Core cannot decide which type holds the foreign key.

Summary

  • One-to-one is a one-to-many whose foreign key is unique; name the dependent with HasForeignKey<T> when needed.
  • Skip navigations give many-to-many without a join class; EF Core creates and maintains the join table.
  • Use an explicit join entity whenever the link needs data or extra behavior.
  • The join table's composite key stops duplicate links.

Next: Fluent API relationship configuration