Many-to-many Relationship

Improve EF Core performance with EF Extensions

Many-to-many Relationship

Earlier in Entity Framework, the many-to-many relationship was classified as two one-to-many relationships. To make it work the developer must create a joining entity class.

Now in Entity Framework Core 5.0, it will have full support for many-to-many relations without explicitly mapping the join table.

  • The navigation properties skip the join table and directly point to the other entity.

  • It will result in writing cleaner queries and simplify the use of the query result.

Let's consider the following model.

public class Movie
{
    public int MovieId { get; set; }
    public string Name{ get; set; }
    public Actor Actor { get; set; }
    public List<Genre> Genres { get; set; }
}

public class Genre
{
    public int GenreId { get; set; }
    public string GenreName { get; set; }
    public List<Movie> Movies{ get; set; }
}

As you can see that Movie class contains a collection of Genres, and Genre class contains a collection of Movies. EF Core 5.0 recognizes this as a many-to-many relationship by convention and there is no need for configuration in OnModelCreating.

When you create migration or call the EnsureCreatedmethod, it will create the following tables including the join table.

Let's insert some movies and genres.

EF will then automatically create rows in the join table.

References

Last updated