Entity-framework – How to delete child entities before parent with Entity Framework CF

databaseentity-frameworkentity-framework-4.1

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?

Best Solution

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();