Here is an example of how to model a many-to-many relation with Entity Framework using code first.

UseCase: one user can have multiple roles and one role can have muliple users. This results in a many-to-many relationship between user and role.

What I like to model looks like this:

many-to-many relation between user and role

many-to-many relation between user and role

We need to two entities: User and Role.

User.cs

public partial class User
{
    public User()
    {
        this.Roles = new HashSet<Role>();
    }
    
    public int Id { get; set; }
    public string Name { get; set; }
    
    public virtual ICollection<Role> Roles { get; set; }
}

Roles.cs

public partial class Role
{
    public Role()
    {
        this.Users = new HashSet<User>();
    }
    
    public int Id { get; set; }
    public string Name { get; set; }
    
    public virtual ICollection<User> Users { get; set; }
}

Here is the entity framework fluent configuration for the relation:

UserMap.cs

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        // Table & Column Mappings
        this.ToTable("User");
        this.Property(t => t.Id).HasColumnName("Id");
        this.Property(t => t.Name).HasColumnName("Name");
    }
}

RoleMap.cs

public class RoleMap : EntityTypeConfiguration<Role>
{
    public RoleMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        // Table & Column Mappings
        this.ToTable("Role");
        this.Property(t => t.Id).HasColumnName("Id");
        this.Property(t => t.Name).HasColumnName("Name");

        // Relationships
        this.HasMany(t => t.Users)
            .WithMany(t => t.Roles)
            .Map(m =>
                {
                    m.ToTable("UserRoles");
                    m.MapLeftKey("UserId");
                    m.MapRightKey("RoleId");
                });
    }
}

Further Reading: