Reputation: 3397
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?
Upvotes: 26
Views: 25083
Reputation: 10851
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);
Upvotes: 27