Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework many-to-many self-reference

I have an entity User. Each User is supposed to have many Friends and Teachers. With EF Code First I am a little bit confused on how to achieve what I want. I saw examples of self reference, but not many-to-many. For example:

public class Employee
{
  #region Properties

  public int EmployeeID { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }

  public int? ManagerID { get; set; }
  public Employee Manager { get; set; }

  #endregion
}

and the modelBuilder:

modelBuilder.Entity<Employee>().
      HasOptional(e => e.Manager).
      WithMany().
      HasForeignKey(m => m.ManagerID);

How to create an entity with self-reference in my case, where there are Friends (if a is friend with b this means that b is friend with a) and Teachers (if a is teacher of b, b is student of a)?

Sorry if there already exists a similar thread. Any help is greatly appreciated.

like image 781
Unknown Avatar asked Mar 09 '12 19:03

Unknown


1 Answers

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).

like image 193
Unknown Avatar answered Sep 23 '22 02:09

Unknown