Where does validation check go in repository pattern?
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:
- Get the user by userId.
- Call delete after validation has been done on the user.
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
//Fro开发者_如何转开发m the UserRepository.
User GetUser(int userId);
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.
精彩评论