Question

I know that in SQL Server I can use delete on cascade when I delete a parent row in a table, but in some places I read that is better to implement this logic in the application (repository) instead of delete on cascade in SQL Server.

So I have two questions. First, if I don't use on delete cascade in SQL Server, how to solve this situation with Entity Framework.

  1. user A adds the parent register and its children to the context
  2. user B adds a new child to the parent register. So user A does not have this child in the context
  3. user A deletes the parent and all the children that are loaded in his context. These children do not include the new child added by user B.

Well, in practice, there is no problem, when user A tries to delete the parent, there is an exception for referential integrity, and the need to load all its children and try again.

This is an extra work for SQL Server, because it needs to send to the user A all the registers again.

If I use delete on cascade in SQL Server, this problem does not exist, so I think is a good option.

So my second question is, is a good idea to use on delete cascade in SQL Server (or other database) or is better to implement this case in the business logic (repository)?

Thanks.

Was it helpful?

Solution

It's a matter of personal preference - I hear valid arguments for both options.

What is more obvious, more understandable to you?

  • Do you prefer to have automagic deletion? Then use ON DELETE CASCADE

  • or do you prefer to be in full control of these situations to know exactly when and what is being deleted? Then implement it in your own custom code

There's no right or wrong, no "better" or "worse" - it's more about your own personal preference and how you feel more comfortable with the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top