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.

One thought on “Entity Framework Self Tracking Entities Cascade Delete Fails

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>