简体   繁体   中英

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 ?

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, ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM