I'm building a micro-service API, and breaking down an existing stored procedure and moving some logic into the API (the stored procedure is too big and we cannot do the unit test on it properly).

For the micro-service API, we are using controller, service and repository pattern but unsure where some of the logic should go.

  1. Trimming phone number for storing into the database, and other data preparation
  2. Moving default validation logic from the stored procedure to C# (e.g. if the sortExpression is invalid we set it the variable to CreatedDate)

For both, I'm currently putting it in the service layer.

For (2), is it ok to do this kind of logic in C#?

I did some research, and they all say business logic should go to service but does this count as business logic? It's more like data preparation and validation for the database

  • Yes, you should be avoiding business logic in your Stored Procedures. The basic Idea of the Stored Procedures should be to server your data needs. – Zeeshan Adil Apr 11 at 14:29
  • @ZeeshanAdil, so should these type of logic be done in service or repository? that's my main concerns. Cause it seem like it's more database related, so shouldnt it be in the repository, which is closer to the database layer? or is service layer ok? – user308553 Apr 11 at 14:42
  • Very broad and almost entirely opinion-based, since there's a whole range of viable designs. Anyone who would tell you that doing it in way X or Y is definitely right or wrong is... well, biased. What is factually true is that databases make for bad programming environments (T-SQL barely qualifies as a structured programming language), and so putting any non-trivial logic in a stored procedure tends to be painful in terms of development and maintenance. There are valid reasons to do so anyway (performance, centralizing logic, permission issues...) but again: very broad. – Jeroen Mostert Apr 11 at 14:50
  • @user308553 again, the responsibility of the repository layer (which is not a good idea) is to serve your data needs. Trimming phone numbers is a business logic and a business might think of changing that in future – Zeeshan Adil Apr 11 at 14:57
  • If you put a bunch of phone number logic in a T-SQL stored procedure and then want to transition to Oracle or MySql, you're going to have to re-write the code for the target platform. If instead your application handles the logic and just depends on the database to store data, you just have a simple INSERT statement at the database level, which is very portable. – Patrick Tucci Apr 11 at 15:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.