Can EF automatically delete data that is orphaned, where the parent is not deleted?

It is actually supported but only when you use Identifying relation. It works with code first as well. You just need to define complex key for your ChildObject containing both Id and ParentObjectId:

modelBuilder.Entity<ChildObject>()
            .HasKey(c => new {c.Id, c.ParentObjectId});

Because defining such key will remove default convention for auto incremented Id you must redefine it manually:

modelBuilder.Entity<ChildObject>()
            .Property(c => c.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Now calling to parentObject.ChildObjects.Clear() deletes dependent objects.

Btw. your relation mapping should use WithRequired to follow your real classes because if FK is not nullable, it is not optional:

modelBuilder.Entity<ParentObject>().HasMany(p => p.ChildObjects)
            .WithRequired()
            .HasForeignKey(c => c.ParentObjectId)
            .WillCascadeOnDelete();

Leave a Comment