Entity Framework Core Intermediate

Many-to-many relationships

A many-to-many relationship links rows on both sides freely, such as students and courses or posts and tags. This lesson shows the simple skip-navigation version EF Core creates for you, and the explicit join entity you need when the link itself has data.

Posts and tags
  1. StartPostHas a Tags collection
  2. Step 2PostTag join tablePostsId and TagsId, created by EF Core
  3. Step 3TagHas a Posts collection
  4. EndNeed extra data?Make the join table an entity with UsingEntity

The simple way

Give each side a collection of the other. EF Core creates the join table (PostTag) with a composite key behind the scenes, and you never touch it directly.

C#
public class Post
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public List<Tag> Tags { get; } = [];
}

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List<Post> Posts { get; } = [];
}

// Adding a link is just adding to the collection
var post = await db.Posts.Include(p => p.Tags).FirstAsync(p => p.Id == id);
var tag = await db.Tags.FirstAsync(t => t.Name == "efcore");
post.Tags.Add(tag);
await db.SaveChangesAsync();   // INSERT INTO PostTag

When the link has its own data

If you need to store something about the link, such as when a student enrolled and their grade, make the join table a real entity with its own DbSet.

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 DateTime EnrolledAt { get; set; }
    public int? Grade { get; set; }
}

modelBuilder.Entity<Student>()
    .HasMany(s => s.Courses)
    .WithMany(c => c.Students)
    .UsingEntity<Enrollment>();   // keeps skip navigations AND the payload

Querying

  • Filter through the collection: db.Posts.Where(p => p.Tags.Any(t => t.Name == "efcore")).
  • Load related rows with Include(p => p.Tags), or project only what you need with Select.
  • To remove a link, load the collection and Remove the item; EF Core deletes the join row, not the Tag.
  • Index the second key column of the join table for queries from the other side.

Interview question

How do you model a many-to-many relationship that needs extra columns on the link?

Create a join entity, such as Enrollment with StudentId, CourseId and the extra columns, and configure HasMany().WithMany().UsingEntity<Enrollment>(). EF Core uses that class as the join table, so you can query and update the payload through a DbSet<Enrollment>, while Student.Courses and Course.Students still work as direct navigations.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.