Search code examples
c#.net-coreentity-framework-coremany-to-manyself-reference

Error with many-to-many relationship in Entity Framework Core


I'm trying to achieve the Following scheme with EF Core.

Here is my class

public class User
{
    this.Id = Guid.NewGuid().ToString();
    public ICollection<User> Followers { get; set; } = new List<User>();
    public ICollection<User> Following { get; set; } = new List<User>();
}

Here is my configuration

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders;

public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder
            .HasMany(m => m.Followers)
            .WithMany(m => m.Following)
            .Map(x => x.MapLeftKey("UserId")
            .MapRightKey("FollowerId")
            .ToTable("UserFollowers"));

    }
}

Here is Error :

Severity Code Description Project File Line Suppression State Error CS1061 'CollectionNavigationBuilder<User, User>' does not contain a definition for 'WithMany' and no accessible extension method 'WithMany' accepting a first argument of type 'CollectionNavigationBuilder<User, User>' could be found (are you missing a using directive or an assembly reference?) Gapped.Entities E:\Projects\Generic\GappedProfileAPI\GappedBaseAPI-skeleton\Gapped.Entities\Models\Configurations\Users\UserConfiguration.cs 50 Active


Solution

  • EF Core doesn't (yet) support automatic many to many relationships. You have to provide the link table between the 2 ends:

    public class User
    {
        this.Id = Guid.NewGuid().ToString();
        public ICollection<Follower> Followers { get; set; } = new List<Follower>();
        public ICollection<Follower> Following { get; set; } = new List<Follower>();
    }
    
    public class Follower
    {
        public User User {get;set;}
        public User Follower {get;set;}
    }