1110
1110

Reputation: 6839

How can I add additional field in N to N junction table in entity framework

I have two tables Group and 'User'. User can join to many groups. So I created this two objects and join them in fluent api:

public class Group
    {...
public virtual ICollection<ApplicationUser> Members { get; set; }

and:

public class ApplicationUser
    {...
public virtual ICollection<Group> MemberInGroups { get; set; }

And I mapped them in fluent api:

modelBuilder.Entity<Group>()
                        .HasMany(c => c.Members)
                        .WithMany(x => x.MemberInGroups)
                        .Map(a =>
                        {
                            a.ToTable("UsersInGroups");
                            a.MapLeftKey("GroupId");
                            a.MapRightKey("UserId");
                        });

How I can add here one more column in junction table like JoinDate?

Upvotes: 1

Views: 1355

Answers (1)

JotaBe
JotaBe

Reputation: 39055

EF doesn't support it. If you need a junction table with extra columns, that table must be mapped to an entity itself, and you lose the direct many-to-many navigation.

You'll have two many-to-one and one-to-many relationships instead, and you'll need to give two hops two navigate between then, i.e from an enttity to the junction table entity (which will be its child) and from the junction table entity to the collection of related entities of the other side of the relationship.

See this SO Q&A:

Many to many mapping with extra fields in Fluent API

Upvotes: 2

Related Questions