6

In my MS SQL Server 2008 database I have self-referenced table with categories for hierarchy (ID and ParentID). Table have a self Foreign Key constraint and "Instead of Delete" trigger to perform deleting the full node with its children.

To manage data I'm using Entity Framework (4.3), with the model generated from DB with self-tracking entities and ObjectContext (generated by VS template). EDM also have self-referenced association on "category" entity.

I am faced with problem when trying to delete any parent row that has at least one child row.

After I call:

Entity.MarkAsDeleted();
Context.SaveChanges();

In SQL Server Profiler I see that EF first generates an update statement to set ParentID of child row(s) to null and then deletes parent row! Of course cascade rule in DB doesn't work and child nodes remains both in EF context and DB.

I've tried to set association rule "On delete" to "Cascade" and to "None" but it doesn't make sense...

How can I perform a cascade delete in a self-referenced table with EF, or at least how to prevent EF from updating parent IDs of child rows?

PS: here I found exactly the same problem without answer (MSDN)

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Korj
  • 61
  • 3

0 Answers0