开发者

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 collec开发者_运维问答tion. 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");
        });
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜