I am working on a .NET 6 project with EF core 6.0. The project is build using Clean Architechture and CQRS pattern.
My question is more general and I am looking more for opinions rather than straight answers.
So imagine that I have a command that deletes user from the database. Let's call it DeleteUserByIdCommand
. The command takes a user id and checks if the user exists, if the user exists, it will be deleted.
At the end of the command I am calling context.SaveChanges()
so the deletion actually happens in the database. The problem comes when I add another command, let's name it DeleteUsersByIdBulkCommand
. In this command, I want for the sake not repeating myself, to use my existing DeleteUserByIdCommand
. The new command takes an array of user ids. This way, though, if I have 100 users to delete, the SaveChanges()
and the get requests will be executed 100 times, which is terrible for performance.
For me there are only two simple options, I have tried both:
- Just not to reuse the
DeleteUserByIdCommand
and write new code in the new code. The problem with that is if, for example, I want to extend the command with let's say deleting the user from some other database or third party API, I will have to change the code on two places. - The other solution, is to have a property in the
DeleteUserByIdCommand
which is calledShouldCallSaveChanges
and it is boolean. By default it is true, but when I am calling this command from theDeleteUsersByIdBulkCommand
it will be set to false, and I will just executeSaveChanges()
after the foreach.
My question is if there is some strict rule for cases like this one? Is it a problem to repeat code here, or maybe there is some specific solution for this case. I would like to hear your input or some other suggestions you may have :)