Self-referencing many-to-many recursive relationship code first Entity Framework
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");
}
);
}
You can get this to work in EF 4 CTP5 using Model-First, but the CTP5 Code First has too many bugs with self-referential and polymorphic query configurations to use Code First for such scenarios. Morteza Manavi (see other answer) has documented several of them on his blog.
If I am correct you can influence the many to many table name with this code:
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");
}
);
}
hope this helps.