7

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.

Unknown
  • 1,377
  • 1
  • 15
  • 33
  • How about this one? http://blogs.msdn.com/b/wriju/archive/2011/05/14/code-first-ef-4-1-building-many-to-many-relationship.aspx – Magnus Karlsson Mar 09 '12 at 19:53
  • The example shows only many-to-many, without self-reference, which is quite easy and does not even require a modelBuilder. Anyway thank you for your help. – Unknown Mar 10 '12 at 08:05

1 Answers1

10

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

Unknown
  • 1,377
  • 1
  • 15
  • 33