Search code examples
c#entity-frameworkmany-to-manycode-first

Self-referencing many-to-many recursive relationship code first Entity Framework


I can't seem to make this work at all

class Member
{
    public virtual IList<Member> Friends { get; set; }
    [Key]
    public int MemberId { get; set; }
    public string Name{ get; set; }
}

I tried adding Mappings but in vain. Is there a way to do so with CTP5?


Solution

  • By convention, Code First will take uni-directional associations as one to many. Therefore you need to use fluent API to let Code First know that you want to have a many to many self referencing association:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Member>().HasMany(m => m.Friends).WithMany().Map(m =>
            {
                m.MapLeftKey("MemberId");
                m.MapRightKey("FriendId");
                m.ToTable("MembersFriends");
            }
        );
    }