EntityFramework.Docs
EntityFramework.Docs copied to clipboard
Provide more many-to-many mapping examples, including with explicitly mapped join entities
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.
- ID: fe1acf84-126c-f01d-b39a-ab077819351f
- Version Independent ID: 5d3bdd6d-ad0e-e306-5aef-0d5adea892b6
- Content: Complex Query Operators - EF Core
- Content Source: entity-framework/core/querying/complex-query-operators.md
- Product: entity-framework
- Technology: entity-framework-core
- GitHub Login: @smitpatel
- Microsoft Alias: avickers
@blogcraft If you want to use explicit joins, then map the join table to an entity type and proceed as before.
Thanks for the response! But I didn't understand. (Sorry 😅) Can I get a code example?
@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;
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 not sure if it is relevant but EF Core Power Tools has an option to generate join Entities with EF Core 6.
@ErikEJ Thanks a lot! It was exactly what I needed.