2

I want to be able to access followers and following as collections from my user entity:

public class User
{
  public int Id { get; set; }
  public ICollection<User> Followers { get; set; }
  public ICollection<User> Following { get; set; }
}

This would then map to a table:

UserFollowers(UserId, FollowerId)

I can get the table generated correctly and working for followers with some fluent config:

modelBuilder.Entity<User>().HasMany(m => m.Followers).WithMany().Map(x => x.MapLeftKey("UserId").MapRightKey("FollowerId").ToTable("UserFollowers"));

The tricky part is letting EF know that the Following collection should map to the same table but with FollowerId mapping to the User.

I have tried simply adding:

modelBuilder.Entity<User>().HasMany(m => m.Following).WithMany().Map(x => x.MapLeftKey("FollowerId").MapRightKey("UserId").ToTable("UserFollowers"));

but I get an error:

The EntitySet 'UserUser1' with schema 'dbo' and table 'UserFollowers' was already defined. Each EntitySet must refer to a unique schema and table.

How do I resolve this?

Paul Hiles
  • 9,558
  • 7
  • 51
  • 76

1 Answers1

4

you can do this using one mapping like this.

modelBuilder.Entity<User>().HasMany(m => m.Followers).WithMany(m=>m.Following ).Map(x => x.MapLeftKey("UserId").MapRightKey("FollowerId").ToTable("UserFollowers"));
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92