Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF CF Configure many-to-many mapping manually

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");
like image 332
mynkow Avatar asked Mar 20 '11 11:03

mynkow


1 Answers

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");
        });
    }
}
like image 113
Morteza Manavi Avatar answered Sep 27 '22 19:09

Morteza Manavi