title: Entity Framework does not cascade delete child entities
body: <p>I have a parent and child entities. In the db, the relationship is set to `ON DELETE CASCADE'. </p>
  
  <p>The EF code-first Fluent api mapping for the relationship is:</p>
  
  <pre><code>this.HasMany(t =&gt; t.Children)
      .WithOptional()
      .HasForeignKey(d =&gt; d.ParentId)
      .WillCascadeOnDelete();
  </code></pre>
  
  <p>The code to delete an entity is:</p>
  
  <pre><code>public virtual void Delete(Parent entity)
  {
      DbEntityEntry dbEntityEntry = dataContext.GetEntry(entity);
      if (dbEntityEntry.State != EntityState.Deleted)
      {
          dbEntityEntry.State = EntityState.Deleted;
      }
  
      else
      {
          dbSet.Attach(entity);
          dbSet.Remove(entity);
      }
  }
  </code></pre>
  
  <p>When I try to delete the parent entity, I get the following exception:</p>
  
  <blockquote>
    <p>The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.</p>
  </blockquote>
  
  <p>As cascade delete is already set correctly, doesn't EF automatically perform a cascade delete?</p>
  
  <p>Or should I manually delete the children before deleting the parent entities?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I added the following code to the above <code>Delete</code> method:</p>
  
  <pre><code>if (entity.Children != null)
  {
      dataContext.Set&lt;Child&gt;().RemoveRange(entity.Children);
  }
  </code></pre>
  
  <p>The children and parent records are deleted succesfully.</p>
  
  <p>Is the above code really necessary? Shouldn't EF/SQL Server handle cascade delete?</p>