I am making an App which will have the Following functionality. But I am stuck at this. I have come up like this.
public class User
{
public int Id { get; set; }
public ICollection<User> Followers { get; set; }
public ICollection<User> Following { get; set; }
}
And the followers table will be
public class Followers
{
public int UserId { get; set; }
public int FollowerId { get; set; }
}
But in this approach how will Entity framework will know that which are Followers and which I am following? Thanks in Advance.
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();
}
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).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With