EntityFramework.Docs icon indicating copy to clipboard operation
EntityFramework.Docs copied to clipboard

Provide more many-to-many mapping examples, including with explicitly mapped join entities

Open blogcraft opened this issue 2 years ago • 6 comments

Now that relationship tables are gone with EF Core 6, there must be some docs that explain how to join many to many tables.

Bejore:

from x in xTable join xy in xyTable on x.Id equals xy.xId join y in yTable on xy.yId equals y.Id ....

Now: ???

xyTable is no longer mapped to explicit entity types, so how to do a join? and multiple joins with multiple many to many relationships?


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

blogcraft avatar Dec 30 '21 01:12 blogcraft

@blogcraft If you want to use explicit joins, then map the join table to an entity type and proceed as before.

ajcvickers avatar Jan 03 '22 11:01 ajcvickers

Thanks for the response! But I didn't understand. (Sorry 😅) Can I get a code example?

blogcraft avatar Jan 03 '22 14:01 blogcraft

@blogcraft For example, with a many-to-many between posts and tags:

public class Post
{
    public int Id { get; set; }
    public List<Tag> Tags { get; } = new();
}

public class Tag
{
    public int Id { get; set; }
    public List<Post> Posts { get; } = new();
}

Create an entity type for the join table:

public class PostTag
{
    public int PostId { get; set; }
    public int TagId { get; set; }
}

And map it:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<Post>()
        .HasMany(e => e.Tags)
        .WithMany(e => e.Posts)
        .UsingEntity<PostTag>();
}

Now use it in your queries as before:

var query = from x in context.Posts
    join xy in context.Set<PostTag>() on x.Id equals xy.PostId
    join y in context.Tags on xy.TagId equals y.Id
    select x;

ajcvickers avatar Jan 10 '22 10:01 ajcvickers

Thanks for the example, I'll give it a shot!

Sadly upgrading to EF 6 is more of a hassle thanks to this 😕 Our model is crawling with many to many relationships and we do database first reverse engineer with EF Core Power Tools every other day. Is there any benefit of doing explicit joins? I'm really considering staying with EF 5.

blogcraft avatar Jan 12 '22 19:01 blogcraft

@blogcraft not sure if it is relevant but EF Core Power Tools has an option to generate join Entities with EF Core 6.

ErikEJ avatar Jan 12 '22 19:01 ErikEJ

@ErikEJ Thanks a lot! It was exactly what I needed.

blogcraft avatar Jan 12 '22 22:01 blogcraft