Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete child entities before parent with Entity Framework CF?

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?

like image 245
quakkels Avatar asked Mar 08 '12 15:03

quakkels


2 Answers

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(); 
like image 106
quakkels Avatar answered Sep 27 '22 23:09

quakkels


EF6

context.Children.RemoveRange(parent.Children) 
like image 27
Eng. Samer T Avatar answered Sep 27 '22 22:09

Eng. Samer T