4

I have a parent and child entities. In the db, the relationship is set to `ON DELETE CASCADE'.

The EF code-first Fluent api mapping for the relationship is:

this.HasMany(t => t.Children)
    .WithOptional()
    .HasForeignKey(d => d.ParentId)
    .WillCascadeOnDelete();

The code to delete an entity is:

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);
    }
}

When I try to delete the parent entity, I get the following exception:

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.

As cascade delete is already set correctly, doesn't EF automatically perform a cascade delete?

Or should I manually delete the children before deleting the parent entities?

EDIT

I added the following code to the above Delete method:

if (entity.Children != null)
{
    dataContext.Set<Child>().RemoveRange(entity.Children);
}

The children and parent records are deleted succesfully.

Is the above code really necessary? Shouldn't EF/SQL Server handle cascade delete?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263

0 Answers0