Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing children entries from parent causes error on SaveChanges

I am getting the following error:

The association between entity types 'Docket' and 'DocketLine' has been severed but the foreign key for this relationship cannot be set to null. If the dependent entity should be deleted, then setup the relationship to use cascade deletes.

The issue comes about because I have a Docket (header) than has multiple children (DocketLines), and I am doing an update where I am adding new Lines to the docket header, and I am just adding those new DocketLines to the Docket.DocketLines collection (which works fine). But when I attempt to remove a DocketLine from the same collection using Docket.DocketLines.Remove(deletedLine), then this generates the error message above. Any idea why?

I had to change my code to remove the Lines directly from the _context.DocketLines.Remove/RemoveRange(...) collection in the end, and this works, but it seems odd that I would add new items to a child collection to insert new DocketLines, but couldn't remove items from that same collection to remove DocketLines.

like image 661
Grant Nilsson Avatar asked Apr 12 '16 23:04

Grant Nilsson


1 Answers

Inside the DbContext/OnModelCreating method, comment the OnDelete behaviour of the entity that is giving you that problem:

enter image description here

That will allow you to avoid that problem.

like image 159
X.Otano Avatar answered Oct 14 '22 08:10

X.Otano