I'm building and MVC project using Entity-Framework 6 (code first).
My database Data Models (code first):
public class ParentNode
{
public int ParentNodeId { get; set; }
public string SomeParentData { get; set; }
//FK
[Required]
public int ChildNodeId { get; set; }
public virtual ChildNode ChildNode { get; set; }
}
public class ChildNode
{
public int ChildNodeId { get; set; }
public string SomeChildishData { get; set; }
//References to this table/model
public virtual ICollection<ParentNode> ParentNodes{ get; set; }
}
The issue: Deleting multiple ChildNodes
- I won't rely on cascade delete
- ParentNode->ChildNode has a many to one relation. In case I need to delete one ChildNode, I first delete the ParentNode then the ChildNode ()
- Deleting just one ChildNode will be done like this:
Deleting one ChildNode: no problem (if only 1 is present in the list)
Deleting multiple ChildNodes: FK Null reference error occurs
{
...
foreach(ParentNode parentToDelete in parentNodeList)
{
db.Entry(parentToDelete).State = EntityState.Deleted;
db.SaveChanges();
}
foreach(ChildNode childToDelete in childNodeList)
{
db.Entry(childToDelete).State = EntityState.Deleted;
db.SaveChanges(); //Error Exception occurs here!!
}
...
}
error message:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
Table rows state when error occurred
Parent
PK: RestaurantMenuCategoryId
FK: restaurantMenuNameId
Child
PK: restaurantMenuNameId
As you can see parent table still has a reference to child row restaurantMenuNameId == 2, whilst the expected behaviour is that parent reference should have been deleted before accessing the child table.
My observations:
- By looking at the database, it seems that when db.SaveChanges() occurs for the parent node, even though the DELETE query in the database hasn't occurred, the code keeps on moving asynchronously. Synchronous behaviour should be used, instead of a fire and forget?
- An other possibility is that DbContext isn't updated after the parent delete, this could have been true if by looking at the db the parent rows were deleted but they were "still there". So what is going on?
Question: Please let me know what the problem is, what are the main topics that are related to this issue?