5

我有一个现有的数据库。目前我正在尝试首先使用实体​​框架代码将我的新实体对象映射到该数据库。下面是具有朋友集合的用户类。如您所见,这是同一张表的多对多关系。如何将此关系映射到具有列“user_id”和“friend_id”的表“user_friend”。

public class User
{
    private ICollection<User> _friends = new List<User>();
    public ICollection<User> Friends { get{return _firends;} }
}

moduleBuilder.Entity<User>().HasMany????.ToTable("user_friend");
4

1 回答 1

6

为此,您需要下拉到 fluent API:

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");
        });
    }
}
于 2011-03-20T14:54:27.780 回答