I have two tables, one table A that is the parent and other table B that is the children (1:N relationship).
If I want to delete the children records in the table B when I delete the parent in the table A, if I don't use cascade on delete in the data base, I would do it in the following way:
- User A load the parent record in her context, then load all the children records in the context, mark all as deleted.
- Other user add a new children.
- User A save changes. Get an error of reference integrity because the register added by the second user is not in her context.
In this case, the first user can try load all the children again when the exception is raised, but a third user can add a new children and have the same problem. In theory, this can occur all the time and the first user wouldn't delete the parent.
For that reason, I am thinking to use a transaction to do the work.
- First user starts a transaction.
- First user mark as deleted the parent and save the changes. The parent is blocked in the database.
- First user load all the children, marked as deleted.
- First user save the changes.
In this case, I have a doubt, when the parent register is blocked by the first user, the ID of this parent can be use by other user as foreign key of a children record? Or the database does not allow to use the ID because in theory is a deleted record?
If the database does not allow to use the ID, the second user will get an exception when try to add a new children, for reference integrity, because the parent does not exists. So the problem is solved. It is not needed to do anything else.
However, if the database allows to use the ID of the blocked parent, I need to do two things:
In the method that delete the parent:
- Load the parent, mark it as deleted and save changes. This block the register.
- Load the children, mark them as deleted an save the changes.
- accept the transaction.
In the method that added a children
- Load the parent. If is blocked, the method wait until the register is free.
- Add the new children.
- Accept changes.
Really is not needed to load the parent in the context to delete the children, it would be an extra query to the database.
If the parent does not exists, get an exception an is not needed to do anything else, the user that try to added a new register now that is because the parent was deleted.
If the parent exists, the children can be added.
So I have two questions.
is a good idea to use a transaction to delete a parent record to ensure that all the children are deleted?
If a transaction is a good option, when the parent is blocked, the data base does not allow to use the parent ID to add a new record or I need to do the solution to load the parent in the method that delete the children?