0

Here is the snippet of code where I am deleting my object:

var foo = this.repository.GetFoo();

foreach (var item in foo.RelatedItems.ToList()) {
    if (x == y) {
        //Update happens here; this isn't executing however.
    } else {
        //This code block is executed; this is where I am telling the context to mark this object for deletion.
        foo.RelatedItems.Remove(item);
    }
}

this.repository.Save();

When the .Save() is called, I am getting an error: "Cannot insert value NULL into column". I used the profiler to see what SQL was actually getting executed and it was:

update dbo.RelatedItems
set foreignKey = null
where id = X

I would expect a delete statement to be executed here, but, for some reason it's trying to update the record by setting the foreign key to null.

Edit

I added the following code to my repository class to solve the issue:

public void DeleteItem(Item item) {
    context.Entry(item).State = System.Data.EntityState.Deleted;
}
Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
  • 2
    See this related question: http://stackoverflow.com/questions/2554696/ef-4-removing-child-object-from-collection-does-not-delete-it-why – akatakritos Oct 25 '12 at 14:09
  • @akatakritos - Thanks, that was my problem. I spent some time searching for my error before posting, but, to no avail. I'm going to leave the post here in hopes that my wording + Google indexing helps someone else out. :) If you post an answer I'll accept it. – Justin Helgerson Oct 25 '12 at 14:34

1 Answers1

0

See this related question: EF 4: Removing child object from collection does not delete it - why?

Apparently there is a semantic difference between Remove and Delete where Remove will just orphan the row by removing the foreign key, and Delete will actually take the record out of the table.

User vittore on the other questions suggests

dbcontext.DeleteObject(item);

inside the loop.

Community
  • 1
  • 1
akatakritos
  • 9,836
  • 1
  • 23
  • 29