4

I'm using POCO generated classes - any way that I can tweek the template so that when I remove from a child collection, the item removed is also deleted from the db ?

Or maybe in the partial class I can override something, catch an event ..?

Basically I want Order.OrderDetails.Remove(orderDetail) to remove the orderDetail from db.

I do not want to access the context and do context.OrderDetails.Delete(orderDetail).

sirrocco
  • 7,975
  • 4
  • 59
  • 81

1 Answers1

1

When you remove an object from a collection navigation property, Entity Framework removes the relationship between the objects (nulling the property on the child object that refers to its parent).

If you want to delete a record, you need to mark the object as State = EntityState.Deleted. You can either do that by accessing the context, or if you don't want to, a workaround would be to identify the child objects that have been orphaned in the ChangeTracker, and set their State to Deleted there.

var orphans = context.ChangeTracker.Entries().Where(e => e.State == EntityState.Modified && typeof(e.Entity) is ChildType);
foreach (DbEntityEntry orphan in orphans)
{
    orphan.State = EntityState.Deleted;
}
Paul Taylor
  • 5,651
  • 5
  • 44
  • 68