Looks like you want a many-to-many self-referencing relationship using code first? You don't need the Followers
class. Just define the User
class:
public class User
{
public int Id { get; set; }
public ICollection<User> Followers { get; set; }
public ICollection<User> Following { get; set; }
}
and then write your DbContext
class this way:
public class MyEntities: DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(x => x.Followers).WithMany(x => x.Following)
.Map(x => x.ToTable("Followers")
.MapLeftKey("UserId")
.MapRightKey("FollowerId"));
}
}
A Followers
table will be created in the database along with the Users
table. You can test it with the following code:
using (var db = new MyEntities()) {
var user1 = new User();
var user2 = new User();
var user3 = new User();
user1.Followers = new User[] { user2 };
user2.Followers = new User[] { user3 };
db.Users.Add(user1);
db.SaveChanges();
}
Update
How Entity Framework knows which are followers and which are following? The answer is, it interprets the modelBuilder
statement this way:
Entity<User>
: the subject is User
;
HasMany(x => x.Followers)
: a user has many followers;
WithMany(x => x.Following)
: each follower has many following;
Map(...)
: the link table is Followers
, the left key points to the subject (user), the right key points to the subject's related entity (follower).