I am trying to use EF code-first to delete a db record (deleteMe
) and it's children (deleteMe.Prices
).
foreach (var deleteMe in deleteThese) { // Delete validation if(CanDeleteItem(deleteMe.ItemId)) { db.Entry(deleteMe).State = EntityState.Deleted; foreach (var item in deleteMe.Prices) { db.Entry(item).State = EntityState.Deleted; // cascade delete } } } db.SaveChanges();
However, Entity Framework seems to be unable to track the fact that the child records should be deleted before the parent. I get the error:
The DELETE statement conflicted with the REFERENCE constraint "ItemPrice_Item".
The conflict occurred in database "DEVDB", table "dbo.ItemPrices", column 'Item_ItemId'.
The statement has been terminated.
How would I execute this delete in EF?
I ended up finding a quick line that'd do it for me:
foreach (var deleteMe in deleteThese) { // Delete validation if(CanDeleteItem(deleteMe.ItemId)) { /// deleteMe.Prices.ToList().ForEach(p => db.ItemPrices.Remove(p)); /// db.Entry(deleteMe).State = EntityState.Deleted; } } db.SaveChanges();
EF6
context.Children.RemoveRange(parent.Children)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With