Entity Framework Self Tracking Entities Cascade Delete Fails

This is just a quick FYI if you come across a situation while using self tracking entities where you’re getting weird errors when trying to delete a entity that had cascade delete turned on for related entities.

Instead of doing:

MyEntity.MarkAsDeleted();

myContext.MyObjectSet.ApplyChanges(MyEntity);
myContext.SaveChanges();

You need to first make sure the entity is attached and then call DeleteObject for the cascade to run correctly.

So now the code now becomes:

myContext.MyObjectSet.Attach(MyEntity);
myContext.MyObjectSet.DeleteObject(MyEntity);
myContext.SaveChanges();

Happy cascade delete.