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;
}