title: How to get a list of children in a self-referencing table (Parent-Child) using EF Core?
body: <p>I use the following Model to create a self-referencing table:</p>
  <pre><code>public class Part
  {
      [Key]
      public long PartId { get; set; }
      [Required]
      public string PartName { get; set; }
      public long? ParentPartId { get; set; }
      public Part Parentpart { get; set; }
  
      //Navigation properties
      public ICollection&lt;Part&gt; ChildParts { get; set; } //For self-referencing
  }
  </code></pre>
  <p>The Fluent API is:</p>
  <pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
  //For parts self-referencing
      modelBuilder.Entity&lt;Part&gt;(entity =&gt;
      {
          entity.HasKey(x =&gt; x.PartId);
          entity.Property(x =&gt; x.PartName);
          entity.HasOne(e =&gt; e.Parentpart)
                .WithMany(e =&gt; e.ChildParts)
                .HasForeignKey(e =&gt; e.ParentPartId)
                .IsRequired(false)
                .OnDelete(DeleteBehavior.Restrict);
      });
  }
  </code></pre>
  <p>I can use the following code to get all the parents of a given part:</p>
  <pre><code>[HttpGet]
  public async Task&lt;IActionResult&gt; GetParentPartsList(string partName)
  {
      var q = _sqlServerContext.Parts.Where(x =&gt; x.PartName == partName).Include(x =&gt; x.Parentpart);
  
      while (q.Select(x =&gt; x.ParentPartId) == null)
      {
          q = q.ThenInclude(x =&gt; x.Parentpart);
      }
      q = q.ThenInclude(x =&gt; x.Parentpart);
  
      return Ok(await q.ToListAsync());
  }
  </code></pre>
  <p>I want to get a list of all children for a given part. I searched some threads such as this <a href="https://stackoverflow.com/questions/70475873/self-referencing-parent-child-relationship-one-to-zero-or-one-in-entity-framew">link</a>, but they have a one-one relationship between child and parent while I need a one-many relationship. How can I achieve this?</p>