title: How to remove child one to many related records in EF code first database?
body: <p>Well, I have one-to-many related model:</p>
  
  <pre><code>public class Parent
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public ICollection&lt;Child&gt; Children { get; set; }
  }
  
  public class Child
  {
      public int Id { get; set; }
      public string ChildName { get; set; }
  }
  </code></pre>
  
  <p>What I want to do is clear <code>Parent.Children</code> and remove related child entities from database. I've already tried:</p>
  
  <p><strong>Database context class:</strong></p>
  
  <pre><code>modelBuilder.Entity&lt;Parent&gt;()
              .HasMany(p =&gt; p.Children)
              .WithOptional()
              .WillCascadeOnDelete(true);
  </code></pre>
  
  <p>this works fine, but I still have redundant records in database with <code>Parent_Id = null</code> fields when I do </p>
  
  <pre><code>parent.Children.Clear();
  repository.InsertOrUpdate(parent);
  </code></pre>
  
  <p>in my repository class. Also the same behavior is when I do:</p>
  
  <pre><code>modelBuilder.Entity&lt;Parent&gt;()
              .HasMany(pr =&gt; pr.Children)
              .WithOptional(ri =&gt; ri.Parent)
              .WillCascadeOnDelete(true);
  </code></pre>
  
  <p>with additional <code>Parent</code> property in <code>Child</code> class</p>
  
  <pre><code>public class Child
  {
      ...
      public Parent Parent { get; set; }
      ...
  }
  </code></pre>
  
  <p>or when I do</p>
  
  <pre><code>modelBuilder.Entity&lt;Child&gt;()
              .HasOptional(p =&gt; p.Parent)
              .WithMany(p =&gt; p.Children)
              .HasForeignKey(p =&gt; p.Parent_Id)
              .WillCascadeOnDelete(true);
  </code></pre>
  
  <p>with additional Parent_Id property in <code>Child</code> class</p>
  
  <pre><code>public class Child
  {
       ...
       public int Parent_Id { get; set; }
       ...
  }
  </code></pre>
  
  <p><strong>So, how can I configure cascade deleting correctly? Or how should I supposed to remove those child entities? I assume this is casual task but I'm just missing something.</strong></p>