Entity Framework many-to-many self-reference

Ok, so because a lot of people answered this ;), I searched a little more and I found the solution for my case. The entity looks like:

public class User
{
    public int ID { get; set; }
    public string UserName { get; set; }

    public virtual ICollection<User> Friends { get; set; }
}

The modelBuilder:

modelBuilder.Entity<User>()
                .HasMany(x => x.Friends)
                .WithMany();

And finally I made helper methods BeFriend and BecomeTeacherStudent, which make sure that when you become friend with someone he becomes friend with you (and the respective thing for teacher-student).

Leave a Comment