0

我有一张桌子,我需要多对多的关系,一个例子可以是保持友谊的社交网络。例如:

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }
}

对应表

CREATE TABLE Users (
UserId int,
UserName varchar(255)
);

我需要有一个像这样的表:

CREATE TABLE Friendships(
UserId1 int,
UserId2 int
);

其中两个字段都与Users.UserId. 如何使用 EF 中的注释来实现这一点?

4

2 回答 2

0

Something like this would do it

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }

    public ICollection<User> FriendShips { get; set; }
    public User()
    {
        FriendShips = new HashSet<User>();
    }
}


public class SocialContext : DbContext
{
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>()
        .HasMany(p => p.FriendShips)
        .WithMany()
        .Map(mc =>
        {

            mc.ToTable("userfriends");
        });
    }
}

A single list for each user will keep each users list of friends

Test:

    using (SocialContext ctx = new SocialContext())
    {
        User u = new User()
        {
            UserName = "John"
        };

        User uu = new User()
        {
            UserName = "Jack"
        };

        uu.FriendShips.Add(u);
        u.FriendShips.Add(uu);

        ctx.Users.Add(u);

        ctx.SaveChanges();
    }
于 2013-10-27T08:57:25.597 回答
0

试试这个解决方案

    public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<User> MyFriends { get; set; }

    public virtual ICollection<User> IFriendsForUsers { get; set; }

}

在类 EFDBContext 中: DbContext

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {                
           modelBuilder.Entity<User>().HasMany(t => t.Friends )
          .WithMany(t => t.IFriendsForUsers )
          .Map(c => { c.ToTable("UserFriends"); 
           c.MapLeftKey("UserId"); c.MapRightKey("UserFriendId"); });

          base.OnModelCreating(modelBuilder);
        } 
于 2013-10-27T09:06:47.843 回答