如何在其中配置与主键的多对多关系

How to configure a many to many relationship with primary key too in it

这就是我想要实现的目标:

  modelBuilder.Entity<ApplicationUser>()      
                    .HasMany(u => u.Following)
                    .WithMany(u => u.Followers)
                    .Map(m =>
                            {
                                m.ToTable("FollowTables");
                                m.MapLeftKey("UserId");
                                m.MapRightKey("FollowId");
                            });

在应用程序用户 class 中,我已经配置了如下关注和关注者:

public ICollection<ApplicationUser> Following { get; set; }
public ICollection<ApplicationUser> Followers { get; set; }

关注table应该是这样的:

 public class FollowTable
 {
    [Key]
    public int autoId { get; set; }
    public int UserId { get; set; }
    public int? FollowId { get; set; }
 }

autoId 是主键,UserId 和 FollowId 都是 ApplicationUser 的外键 class 其中 UserId 是用户自己的 ID,FollowId 是用户的 ID following.Its 数据可能如下:

  autoId  UserId  FollowId
   1        4        11
   2        4        12
   3        4        13

现在,我的问题是当我通过 pmc 更新数据库时,它正在创建两个数据库 tables,一个是带有列 (USerId, FollowId) 的 FollowTables,一个是 FollowTables1(autoId, USerId, FollowId)。

如果我从 applicationDbContext 中删除这一行 class:

public DbSet<FollowTable> FollowTables { get; set; }

然后它只创建一个 table 但没有主键。

请有人帮助我。如何正确配置 UserId 和 followId 作为外键,这两个应该映射到 ApplicationUser 的 Id。 我想用那些 Collection 的追随者和追随者 too.how 来做到这一点。

您必须决定是否要使用代表结点 table 的实体。如果您不需要向 table 添加任何其他属性,但 FK 除外,那么我建议您不要将交汇点 table 映射为实体。由于 Entity Framework 会为您处理 table,这对您来说会更容易。

现在,如果您确实需要映射 table,那么您需要删除 many-to-many 流畅 api 配置并更改导航属性的类型:

public ICollection<FollowTable> Following { get; set; }
public ICollection<FollowTable> Followers { get; set; }  

这将创建两个 one-to-many 与结点 table 的关系,many-to-many 关系的显式表示。为此,您还需要对该实体进行一些更改:

public class FollowTable
{
  [Key]
  public int autoId { get; set; }

  public int UserId { get; set; }
  [ForeignKey("User")]
  public ApplicationUser User{ get; set; }

  [ForeignKey("Follow")]
  public int? FollowId { get; set; }
  public ApplicationUser Follow{ get; set; }
}

此外,我认为 FollowId Fk 属性 不应该是可为空的 FK,因为你想表示两个人之间的关系。

如果你问我关于你应该采取什么选择的意见,我建议你不要映射路口 table 如果你打算只拥有那些属性。