I have a table where I need many to many relationships, an example can be a social network where friendships are kept. e.g.:
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
}
corresponding to table
CREATE TABLE Users (
UserId int,
UserName varchar(255)
);
I need to have a table like:
CREATE TABLE Friendships(
UserId1 int,
UserId2 int
);
where both fields are related to Users.UserId
. How can I achieve this with annotations in EF?
Something like this would do it
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public ICollection<User> FriendShips { get; set; }
public User()
{
FriendShips = new HashSet<User>();
}
}
public class SocialContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()
.HasMany(p => p.FriendShips)
.WithMany()
.Map(mc =>
{
mc.ToTable("userfriends");
});
}
}
A single list for each user will keep each users list of friends
Test:
using (SocialContext ctx = new SocialContext())
{
User u = new User()
{
UserName = "John"
};
User uu = new User()
{
UserName = "Jack"
};
uu.FriendShips.Add(u);
u.FriendShips.Add(uu);
ctx.Users.Add(u);
ctx.SaveChanges();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments