How to create a many to many relationship with latest nightly builds of EF Core?

How do you use the Fluent API to create a many to many relationship between two tables in EF7 EF Core? For example, say you have the following tables:

Photos to People database diagram

How would one leverage the modelBuilder in the DbContext class to define a relationship like this?

I've seen this link from the EF team's meeting notes regarding this subject, but it is from last year and am wondering if there is new information on how to approach this in EF7 EF Core.

I am able to create one to many relationships between Photos and PhotosPeople as well as People and PhotosPeople. The database is generated as I'd like it to be, but the navigation between People and Photos now requires interaction with an intermediate entity. I'd like to avoid this.


Solution 1:

This is tracked by #1368. The workaround is to map the join table to an entity:

class Photo
{
    public int Id { get; set; }
    public ICollection<PersonPhoto> PersonPhotos{ get; set; }
}

class PersonPhoto
{
    public int PhotoId { get; set; }
    public Photo Photo { get; set; }

    public int PersonId { get; set; }
    public Person Person { get; set; }
}

class Person
{
    public int Id { get; set; }
    public ICollection<PersonPhoto> PersonPhotos{ get; set; }
}

Be sure to configure PersonPhoto with a composite key:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<PersonPhoto>().HasKey(x => new { x.PhotoId, x.PersonId });
}

To navigate, use a Select:

// person.Photos
var photos = person.PersonPhotos.Select(c => c.Photo);