I'm dealing with this issue as well.
I've overridden the OnSaveComplete method to do some logic after an entity has been saved to the persistent storage.
The situation is as follows:
I am saving an OrderEntity instance using order.Save(true);
I have overridden the OnSaveComplete method of my OrderEntity class. In this overridden method I am checking if related records exist (which should be).
Because I am saving the OrderEntity instance recursively, the related OrderItemCollection (1:n) is also being saved.
My OrderItemValidator class (which is injected) does some checks in the overridden ValidateEntityBeforeSave method. These checks also consist of fetching an OrderCollection.
Here's where the database lock is kicking in.
I figured out the following steps (don't know if it's correct):
- First, the order is recursively being saved and a database lock is on the Order table
- Second, the order items are being saved because of the recursive save of the order
- While the order items are being saved, some logic is being executed by an OrderItemValidator class using injectables. This logic consists of fetches from the Order table. But the lock is still on the Order table from the first step, so a deadlock is created.
How to handle with this situation?
FYI: the foreign keys in the tables are all set to enforce foreign key constraints. If these constraints are being disabled, then the situation works. But that's not my intention.
Perhaps you can tell me if the following is correct as well: it looks like that when the OnSaveComplete method is being called, a lock still is set on the table.
In my example, I've set a breakpoint in first line of the overridden OnSaveComplete method. When I try to open the table in the SQL Server Management Studio, a lock exists on the table and I can't see the data contents of the table.
Wouldn't it be logical that when the OnSaveComplete method is being called, the save is completed and the lock is released? Or I am doing something terribly wrong?
Thanks in advance!
Mathieu