验证检查在存储库模式中去哪里?
假设我有一个名为 User 的实体,它有很多帖子。我的删除帖子的服务如下所示:
void DeletePost(int postId, int userId);
我的验证码去了哪里? (确保用户有删除权限)。我应该在存储库中通过 1 次数据库调用来执行此操作吗?或者我应该在进行 2 个调用的服务层中进行此检查:
- 通过 userId 获取用户。
- 对用户进行验证后调用删除。
我将有 2 个存储库,1 个用于用户,1 个用于帖子,每个存储库如下所示:
// 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);
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
//From the UserRepository.
User GetUser(int userId);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个业务规则,所以我不会将其放在数据访问层(存储库)上。我想说最好的地方是服务层。
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.