0

Setup

I have Visual Studio 2013, use EF6 (Code first with existing db), Resharper 8 and run my debug session against a locally hosted MS SQL server 2012.

The Code snippet

The issue lies withing this method :

    public void Delete(MyEntityClass myEntityInstance)
    {
        DbContext.MyEntityClass.Remove(myEntityInstance);
    }

Following snippet is called right after calling previous method

DbContext.SaveChanges();

Model

MyEntityClass one-to-may relation to MyChildEntityClass

Purpose

I want to delete delete my myEntityInstance along with the child entities (Instances from MyChildEntityClass). I made sure that on the READ I have included the child entities.

Problem

When I run this code, I get an error on SaveChanges() saying I am violating an Foreign Key constraint. Indication that the method is not deleting the child entities along with my parent entity. I know I need to make sure the child entities are loaded in my parent entity to execute a CASCADE delete.

The weird thing is, when I have a breakpoint on DbContext.MyEntityClass.Remove(myEntityInstance); and I inspect the myEntityInstance (hover the myEntityInstance variable and inspect the values of the properties) and then let it run further, the FK column in the child table is set to NULL, while there is a constraint on it)

Has someone else have any experience with such fishy occurrence ?

Segers-Ian
  • 1,027
  • 10
  • 21
  • See this SO post: http://stackoverflow.com/questions/21314113/entity-framework-6-code-first-cascade-delete – CodingGorilla Aug 02 '14 at 15:03
  • check your foreign key in the database, i guess it's `on delete no action` – Yuliam Chandra Aug 02 '14 at 15:04
  • I checked the post already of @CodingGorilla, didn't made me any wiser. I double checked, the database has ON DELETE cascade. – Segers-Ian Aug 02 '14 at 15:14
  • 1
    @IanS. Can you get the SQL that is being generated for the delete that causes the FK reference exception? That might give you a clue - I'm guessing it's attempting to delete the child entity and *that* entity is the one that is causing the exception. – CodingGorilla Aug 02 '14 at 15:24
  • My hunch is that an update statement for the child entities is generatedor even an insert. So, you need to get the SQL generated to confirm this. Use this link on some excellent information about how to go about this. http://blog.oneunicorn.com/ – Dabblernl Aug 02 '14 at 22:47

0 Answers0