0

I have an object like below:

public class AdminMenuItem : BaseEntity
{
    public int? ParentMenuItemId { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }

    public AdminMenuItem ParentMenuItem { get; set; }
}

I added two menuitem. One is A that has not a parent menu. The other one B and A is the parent menu item for the B.

When I delete A, it throws me the exception on below:

The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK_dbo.AdminMenuItem_dbo.AdminMenuItem_ParentMenuItemId".

The conflict occurred in database "A61DB", table "dbo.AdminMenuItem", column 'ParentMenuItemId'. The statement has been terminated

What configuration should I do to also delete child item while deleting parent ? Should I do it manually by putting it in a loop or is there a sufficient way to do it in entity framework 5 ? I try to use WillCascadeOnDelete but I couldnt success.

Also is there way to set child object foreign key to null ? (This is optional)

Barış Velioğlu
  • 5,709
  • 15
  • 59
  • 105

1 Answers1

0

Entity supports ON CASCADE DELETE. Please Look at this:

cascading-deletes-with-entity-framework-related-entities-deleted-by-ef

and this one:

entity-framework-on-delete-cascade

and MSDN article:

how-cascade-delete-really-works-in-ef

Community
  • 1
  • 1
Mostafa Soghandi
  • 1,524
  • 1
  • 12
  • 20
  • Not possible with self-reference though (http://stackoverflow.com/q/528529/861716) – Gert Arnold Jul 14 '13 at 12:50
  • SQL Server also only allows one cascade path, an important limitation for complex object graphs https://support.microsoft.com/en-us/help/321843/error-message-1785-occurs-when-you-create-a-foreign-key-constraint-that-may-cause-multiple-cascade-paths – Eric J. Mar 01 '17 at 21:54