Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 834
Paul Avatar asked Apr 04 '15 03:04

Paul


People also ask

How do you create a many-to-many relationship in EF core?

Many-to-many relationships require a collection navigation property on both sides. They will be discovered by convention like other types of relationships. The way this relationship is implemented in the database is by a join table that contains foreign keys to both Post and Tag .

How do you set up a many-to-many relationship?

To configure many-to-many relationship Using Data Annotations, you need to create the Join Table in the model. The Join Table BookCategory will have properties for the primary key of both the table. It will have two navigational properties one each for Book and Category class.

Is EF core faster than EF6?

EF Core 6.0 performance is now 70% faster on the industry-standard TechEmpower Fortunes benchmark, compared to 5.0. This is the full-stack perf improvement, including improvements in the benchmark code, the . NET runtime, etc. EF Core 6.0 itself is 31% faster executing queries.


1 Answers

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);
like image 114
bricelam Avatar answered Oct 12 '22 23:10

bricelam