小编Chr*_*cki的帖子

Entity Framework Core 3.0 - 创建自引用多对多关系

所以这是我的问题......我试图创建的是一种自我引用的多对多关系。基本上这是我的模型。

public class InformationSystem
{
  public InformationSystem()
  {
     Systems = new HashSet<InformationSystem>();
     ParentSystems = new HashSet<InformationSystem>();
  }
 [Key()]
 public int InformationSystemID { get; set; }
 public string InformationSystemName { get; set; }
 //Navigation properties
 public virtual ICollection<InformationSystem> Systems { get; set; }
 public virtual ICollection<InformationSystem> ParentSystems { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这个想法是,一个系统可以有许多父母,而一个父母可以有许多孩子。我知道如何创建一个自引用实体,其中许多孩子可以有一个父母。让我困惑的是多对多的部分。下面是我的 DbContext。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<InformationSystem>(entity =>
  {
    entity
       .HasMany(e => e.ParentSystems)
       .WithMany(e => e.Systems)
       .OnDelete(DeleteBehavior.Restrict);
  });
Run Code Online (Sandbox Code Playgroud)

然而,在我的 DbContext 上,我收到一个错误,即 .WithMany 不包含 with Many 的定义,该定义将接受类型集合的输入。我知道,当代码首先创建迁移并更新数据库时,基本上需要构建的是链接表。我认为链接表有两列,没有键。一列是 InformationSystemID,一列是 …

c# many-to-many self-referencing-table entity-framework-core

3
推荐指数
1
解决办法
3764
查看次数