Entity Framework cascade delete behavior
Entry Framework approach with Cascade Delete is strange IMHO.
Indeed, imagine that we define cascade delete on Orders to OrderDetails relationship in our model.
If we delete an order, Entity Framework also delete its OrderDetails before deleting the Order. Ok. It’s the normal behavior.
The issue is the fact that instead of using a SQL command like this one:
DELETE OrderDetails WHERE OrderId = xxx
Entity Framework generates one delete per OrderDetails of the Order.OrderDetails collection.
This behavior has two issues:
- It generates many DELETE commands in SQL which is not good for performance
- If you don’t load all Order.OrderDetails first, you will have an exception on SaveChanges because of FK violation.
To avoid this last point, Microsoft recommend to also apply Cascade Delete in DB in addition of the model.
However, in this case deleting all Order.OrderDetails first is useless and bad for performance.
WAQS cascade delete behavior
WAQS assumes that cascade delete also is defined in the DB.
WAQS adds a new entity state: CascadeDeleted
public enum ObjectState
Detached = 0,
Unchanged = 1,
Added = 2,
Modified = 4,
Deleted = 8,
CascadeDeleted = 0x18
With this way, if we delete an Order, using our model with cascade delete relationship, its OrderDetails state become CascadeDeleted.
With this way, entities are removed in Order.OrderDetails, Product.OrderDetails and in context.OrderDetails (like a basic Delete).
But, on SaveChanges, CascadeDeleted OrderDetails are not sent to the server and deleted entities (with or without cascade) become detached.