Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

c# - Entity Framework Core: many-to-many relationship with same entity

I am trying to map many-to-many relationship with the same entity. The User entity has an IList<User> data field for Contacts, which stores users' contacts/friends information:

public class User : DomainModel
{
    public virtual IList<User> Contacts { get; protected set; }
    //irrelevant code omitted
}

When I try to use fluent API to map this many to many relationship, it gives me some trouble. Apparently, when I use HasMany() on the user.Contacts property, it has no WithMany() method to call next. The intellisense from Visual Studio only shows WithOne(), but not WithMany().

modelBuilder.Entity<User>().HasMany(u => u.Contacts).WithMany() 
// gives compile time error: CS1061 'CollectionNavigationBuilder<User, User>' does not contain a definition for 'WithMany' and no extension method 'WithMany' accepting a first argument of type 

So why does this happen? Is there anything I did wrong to map this many-to-many relationship?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So why does this happen? Is there anything I did wrong to map this many-to-many relationship?

No, you didn't do anything wrong. It's just not supported. Current status here.

Many-to-many relationships without an entity class to represent the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table and mapping two separate one-to-many relationships.

With EF-Core you should create the entity for the mapping table. Such as UserContacts. A complete example in the docs, as mentioned in the comments. I haven't actually tested the code below, but it should look something like this:

public class UserContacts
{
    public int UserId { get; set; } 
    public virtual User User { get; set; }

    public int ContactId { get; set; } // In lack of better name.
    public virtual User Contact { get; set; }
}

public class User : DomainModel
{
    public List<UserContacts> Contacts { get; set; }
}

And your modelBuilder.

  modelBuilder.Entity<UserContacts>()
        .HasOne(pt => pt.Contact)
        .WithMany(p => p.Contacts)
        .HasForeignKey(pt => pt.ContactId);

    modelBuilder.Entity<UserContacts>()
        .HasOne(pt => pt.User)
        .WithMany(t => t.Contacts)
        .HasForeignKey(pt => pt.UserId);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...