Rodolphe Beck
Rodolphe Beck

Reputation: 363

How to create a many-to-many with ASPNet EF Core

I want to create a contact list in my application. I therefore created a mapping table between ApplicationUsers:

public class UserContacts
{
    public string UserId { get; set; }
    public virtual ApplicationUser User { get; set; }

    public string ContactId { get; set; }
    public virtual ApplicationUser Contact { get; set; }
}

And then registered the relations between my ApplicationUser and this table:

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

builder.Entity<UserContacts>()
            .HasOne(p => p.User)
            .WithMany(p => p.Contacts)
            .HasForeignKey(p => p.UserId);

And added a property in my ApplicationUser class:

public virtual ICollection<UserContacts> Contacts { get; set; }

But whenever I try to update the database I get the following error:

Cannot create a relationship between 'ApplicationUser.Contacts' and 'UserContacts.User', because there already is a relationship between 'ApplicationUser.Contacts' and 'UserContacts.Contact'. Navigation properties can only participate in a single relationship.

Can you please explain to me what I am missing?

Thanks.

Upvotes: 1

Views: 107

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

You need to add another collection to ApplicationUser:

public virtual ICollection<UserContacts> **Users** { get; set; }

Then change the fluent code to point there (they can't point to same collection):

builder.Entity<UserContacts>()
            .HasOne(p => p.User)
            .WithMany(p => **p.Users**)
            .HasForeignKey(p => p.UserId);

Upvotes: 2

Related Questions