This seems like it should be so simple and yet I have been stuck on this for ages unable to find a clear/good solution.
Quite simply I am building a chat program using Entity Framework to store my user data.
I have a class called User. A User has a list of friends (other users) as shown below
public class User
{
[Key]
public int ID { get; set; }
//whole bunch of other properties like 'username' etc.
public List<User> Friends { get; set; }
public User()
{
this.Friends = new List<User>();
}
}
EF quite happily creates my users table, but I can't for the life of me work out how to write/read the list of users.
One thing I did find whilst looking for answers was this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().
HasMany(m => m.Friends).
WithMany()
.Map(m =>
{
m.ToTable("UsersFriends");
m.MapLeftKey("UserId");
m.MapRightKey("FriendId");
});
}
Which has created a nice table for me with the ID of the user and the ID of the user's friend, but no idea how to get the list to this table. I'm guessing its because the New List() doesn't related to the DBContext..