EF Core Many-to-Many Relationships

A many-to-many relationship allows multiple records of one entity to be associated with multiple records of another. For example, a book can belong to several categories, and a category can contain several books. In EF Core 5.0 and later, you can configure this relationship by convention without defining a separate join entity class. For advanced configurations, see the official EF Core documentation.

⚡ Delete Thousands of Entities Efficiently

Deleting large datasets shouldn't take forever. BulkDelete helps you remove thousands of records without the overhead of regular SaveChanges.

Explore BulkDelete →

Basic Many-to-Many Relationship

language-csharp
|
public class Author
{
    public int AuthorId { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public ICollection<Book> Books { get; set; }
}

public class Book
{
    public int BookId { get; set; }
    public string? Title { get; set; }
    public Author Author { get; set; }
    public ICollection<Category> Categories { get; set; }
}
public class Category
{
    public int CategoryId { get; set; }
    public string? CategoryName { get; set; }
    public ICollection<Book> Books { get; set; }
}

As you can see, the Book class contains a collection of Categories, and the Category class contains a collection of Books. EF Core 5.0 and later recognizes this as a many-to-many relationship by convention, and there is no need for configuration in OnModelCreating.

The Author and Book classes also illustrate a one-to-many relationship, while Book.Categories and Category.Books define the many-to-many relationship.

In a relational database, a many-to-many relationship uses a join table to connect the two entities. Each row represents one association between a book and a category, using a foreign key to identify each related record. EF Core manages this table without requiring a separate C# class.

Before EF Core 5.0, many-to-many relationships required an explicit join entity class and Fluent API configuration.

The following LibraryContext uses the same entities without adding any relationship configuration:

language-csharp
|
public class LibraryContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=LibraryDb;");
    }

    public DbSet<Book> Books { get; set; }
    public DbSet<Author> Authors { get; set; }
    public DbSet<Category> Categories { get; set; }
}

When you apply a migration or call the EnsureCreated method, EF Core creates the necessary tables, including the join table. The following SQL Server example illustrates the generated database structure; you do not need to write this SQL yourself. The Authors table is omitted from the example.

language-sql
|
CREATE TABLE [dbo].[Books] (
    [BookId]   INT            IDENTITY (1, 1) NOT NULL,
    [Title]    NVARCHAR (MAX) NULL,
    [AuthorId] INT            NOT NULL,
    CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED ([BookId] ASC),
    CONSTRAINT [FK_Books_Authors_AuthorId] FOREIGN KEY ([AuthorId]) REFERENCES [dbo].[Authors] ([AuthorId]) ON DELETE CASCADE
);

CREATE TABLE [dbo].[Categories] (
    [CategoryId]   INT            IDENTITY (1, 1) NOT NULL,
    [CategoryName] NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED ([CategoryId] ASC)
);

CREATE TABLE [dbo].[BookCategory] (
    [BooksBookId]          INT NOT NULL,
    [CategoriesCategoryId] INT NOT NULL,
    CONSTRAINT [PK_BookCategory] PRIMARY KEY CLUSTERED ([BooksBookId] ASC, [CategoriesCategoryId] ASC),
    CONSTRAINT [FK_BookCategory_Books_BooksBookId] FOREIGN KEY ([BooksBookId]) REFERENCES [dbo].[Books] ([BookId]) ON DELETE CASCADE,
    CONSTRAINT [FK_BookCategory_Categories_CategoriesCategoryId] FOREIGN KEY ([CategoriesCategoryId]) REFERENCES [dbo].[Categories] ([CategoryId]) ON DELETE CASCADE
);

GO
CREATE NONCLUSTERED INDEX [IX_BookCategory_CategoriesCategoryId]
    ON [dbo].[BookCategory]([CategoriesCategoryId] ASC);

EF Core automatically creates a join table named BookCategory for this relationship. It contains the foreign keys BooksBookId and CategoriesCategoryId, which together form a composite primary key that prevents duplicate associations between the same book and category.

Many-to-Many with a Join Entity

The previous example shows that EF Core creates a join table without requiring a BookCategory class. When you need to work with associations directly or store additional data about them, you can define that class explicitly.

Using the same Book and Category entities, define a BookCategory class:

language-csharp
|
public class BookCategory
{
    public int BookId { get; set; }
    public int CategoryId { get; set; }
}

Then, add the following configuration to the existing LibraryContext:

language-csharp
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Book>()
        .HasMany(b => b.Categories)
        .WithMany(c => c.Books)
        .UsingEntity<BookCategory>();
}

The UsingEntity<BookCategory>() method tells EF Core to use the BookCategory class as the join entity.

EF Core recognizes BookId and CategoryId as foreign keys by convention. Together, they form a composite primary key, ensuring that the same book-category association cannot be added twice. No additional key configuration is needed for this example.

This configuration uses BookId and CategoryId as the join table columns, rather than the convention-generated BooksBookId and CategoriesCategoryId shown in the basic example.

The Book.Categories and Category.Books properties are called skip navigations because they let you access related books and categories directly, without navigating through the BookCategory join entity. You can also extend BookCategory with additional properties, such as a creation date, or add navigations to it when you need to access individual association records.

For more advanced configurations, see Many-to-many with a class for the join entity.

⚡ Delete Thousands of Entities Efficiently

Deleting large datasets shouldn't take forever. BulkDelete helps you remove thousands of records without the overhead of regular SaveChanges.

Explore BulkDelete →

Other Many-to-Many Configurations

EF Core supports additional configurations for many-to-many relationships. The following table summarizes common scenarios and links to the corresponding examples in the official documentation.

Configuration When to use it EF Core documentation
Named join table Customize the name of the join table. Named join table
Custom foreign key names Customize the foreign key properties or column names. Join table foreign key names
Navigations to the join entity Access association records through navigation properties. Navigations to join entity
Join entity with payload Store additional information about an association, such as its creation date. Join table with payload
Unidirectional many-to-many Configure a relationship when only one entity has a collection navigation. Unidirectional many-to-many

Further Reading

  • Many To Many Relationship Configuration — Explore the explicit join entity approach used in earlier versions of EF Core. For current configuration options, use the official documentation linked above.

External Resources

The following videos complement the examples in this article with practical demonstrations of many-to-many relationships in EF Core. Together, they cover convention-based configuration, join entities with additional properties, and more advanced Fluent API customization.

Mastering EF Core Relationships: One-to-One, One-to-Many, and Many-to-Many in .NET — Remigiusz Zalewski

Remigiusz Zalewski demonstrates how EF Core configures relationships using navigation properties, with a practical many-to-many example involving Customer and Reservation. The video shows how EF Core creates the join table automatically and how the resulting relationships appear in SQLite migrations and database records.

Although the tutorial also covers one-to-one and one-to-many relationships, the timestamps below focus on the many-to-many sections relevant to our basic example.

Key timestamps:

This example reinforces how EF Core can manage a many-to-many relationship without an explicitly defined join entity class or additional Fluent API configuration.

EF Core 6: How to build and manage relationships (Part 4) — Building SaaS with Gabriel

Building SaaS with Gabriel demonstrates two ways to model a many-to-many relationship between Student and Course. The tutorial begins with collection navigation properties and an automatically generated join table, then introduces an explicit CourseStudent entity to store additional information about the association.

The demonstration also uses migrations and relationship diagrams to illustrate how the database structure changes when additional properties are introduced.

Key timestamps:

The payload example extends the concepts in our BookCategory example by showing when association-specific data may justify an explicit join entity. The tutorial also discusses preserving an existing join table name during a schema change; this is a migration consideration, not a general requirement for many-to-many relationships.

Deep Dive into Many-to-Many: A Tour of EF Core 5.0 pt. 2 — dotnet

In this Microsoft On .NET episode, Arthur Vickers from the EF Core team explains what happens internally when EF Core configures a many-to-many relationship between User and Group.

The demonstration explores automatically generated join entities, composite keys, model debugging, and explicit Fluent API configuration. It also shows how developers can customize relationship mappings without configuring every detail manually.

Key timestamps:

This video provides a deeper look at the conventions behind many-to-many relationships. It uses EF Core 5 and explores shared-type join entities and more extensive configurations than our introductory UsingEntity<BookCategory>() example. Its main value is showing how convention-based and explicit configurations work together.

Summary

EF Core supports many-to-many relationships through conventions or explicit join entity configuration, depending on your model's requirements.

  • Basic many-to-many: Use collection navigation properties on both entities. EF Core configures the join table by convention.
  • Many-to-many with a join entity: Use UsingEntity<T>() when you need an explicit class to represent associations or store additional information.
  • Other configurations: Use Fluent API to customize table names, foreign keys, or navigation properties.
⚡ Insert Thousands of Entities in Seconds

EF Core inserts taking too long? Use BulkInsert to save thousands of records efficiently with fewer database round trips.

Explore BulkInsert →
  • One-to-One Relationships — Learn how EF Core configures a relationship in which each entity is associated with at most one entity on the other side.
  • Cascade Delete — Understand how EF Core handles related data when entities are deleted.

FAQ

Do I need a DbSet<BookCategory> when using an explicit join entity?

No. UsingEntity<BookCategory>() includes the join entity in the EF Core model without requiring a DbSet<BookCategory> property. You can add one for convenient access to join records, but it is not required to configure the relationship.

Can I configure a many-to-many relationship with a navigation property on only one side?

Yes. EF Core supports unidirectional many-to-many relationships, where only one entity exposes a collection navigation property. Unlike the basic example, this requires explicit relationship configuration. See the official documentation on unidirectional many-to-many relationships.

Does changing from a convention-based relationship to an explicit join entity require a database migration?

Not necessarily. If the new configuration produces the same database schema, a migration may not be needed. However, changes to the join table, foreign key columns, or constraints may require a migration. Always review the generated migration before applying it to an existing database.


Date Modified: 2026-11-18
Author:

Edit this page in GitHub

Got any EF Core Question?