I have an existing database. At the moment I am trying to map my new Entity objects to that DB with entity framework code first. Below is the User class which has a friends collection. As you can see this is a many-to-many relationship to the same table. How can I map this relation to table "user_friend" which has columns "user_id" and "friend_id".
public class User
{
private ICollection<User> _friends = new List<User>();
public ICollection<User> Friends { get{return _firends;} }
}
moduleBuilder.Entity<User>().HasMany????.ToTable("user_friend");
You need to drop down to fluent API for this:
public class User
{
public int UserId { get; set; }
public ICollection<User> Friends { get; set; }
}
public class Context : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(u => u.Friends).WithMany().Map(c =>
{
c.MapLeftKey(u=>u.UserID, "user_id");
c.MapRightKey(f=>f.FriendID, "friend_id");
c.ToTable("user_friend");
});
}
}
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