Lets say I have an entity called User which has many Posts. My service looks like this for the deletion of a post:
void DeletePost(int postId, int userId);
Where does my validation code go? (ensure that the user has permission to delete). Should I do this in the repository with 1 database call? Or should I do this check in the Service layer where I make 2 calls:
I will have 2 repositories, 1 for the user and 1 for the post, each looking like this:
// From the PostRepository.
void Delete(int postId); //May have to add a userId param if I do validation in repository
//From the UserRepository.
User GetUser(int userId);
Validation is an automatic computer check to ensure that the data entered is sensible and reasonable. It does not check the accuracy of data.
As a general rule of thumb, I would say that business logic of this sort should be in the service. Controllers should be light-weight and pass on requests. Further, there may be other clients of your service, not just controllers, so this allows you to keep validation in one place.
A type check will ensure that the correct type of data is entered into that field. For example, in a clothes shop, dress sizes may range from 8 to 18. A number data type would be a suitable choice for this data.
That's a business rule so I wouldn't place it on the data access layer (Repository). I'd say the best place is the service layer.
I think some validation should happen before you get to the repository i.e. in the domain model / business layer.
You may opt to validate in depth and perform validation also in the repository layer; this may or may not be a good idea depending on what the validation is for; if the validation is domain specific then it strikes me that the validation should be in the domain model. On the other hand, if the validation is less domain specific and more general in its nature, then having it in the repository / data access layer means that the validation can be reused across other projects in which the data access layer is reused.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With