当我使用存储库模式时,我应该将业务逻辑放在哪里?
我正在为我的应用程序使用存储库模式。我有一个类用户。用户通过电子邮件来识别。 UserRepository 包含一个方法 CreateUser(User user)。有一条业务规则规定用户应该拥有唯一的电子邮件。
我想实现一个事务,首先检查电子邮件是否正在使用,如果没有,则创建用户。 我应该把负责检查Email唯一性的代码放在哪里?
这绝对是一个业务规则;这是业务逻辑。我认为将此检查放入我的 UserRepository 实现中是不正确的。
I am using the Repository Pattern for my application. I have a class User. User is identified by Email. The UserRepository contains a method CreateUser(User user). There is a business rule saying that users should have a unique Email.
I want to implement a transaction which first checks whether an email is in use and if not, the user is created. Where should I put this code which is responsible for checking the uniqueness of the Email?
This is definitely a business rule; it is business logic. I think it is not correct to put this check in my UserRepository implementation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这类事情通常进入(1)服务或(2)作为数据库约束直接进入模式(并且经常两者都存在)。
使用服务时,您不能直接从客户端代码访问存储库;而是直接从客户端代码访问存储库。您调用一个为您执行有用操作的服务。
例如,类似:
This sort of thing typically goes in either (1) a service or (2) directly into the schema as a database constraint (and frequently both).
Using a service, you don't access the Repository directly from client code; you call a service which does the useful operations for you.
For example, something like:
如果您正在构建一个足够大的应用程序来保证 存储库模式,那么您需要将此验证尽可能靠近数据,可能是数据库约束,例如唯一索引/键。这可以防止由于数据损坏而导致错误泄漏到代码中的情况。
If you're building an application large enough to warrent a repository pattern then you'll want to put this validation as close to the data as possible, probably a database constraint such as a unique index/key. This prevents situations of bugs leaking into code later due to corrupt data.
假设您使用数据库进行存储,那么您绝对应该在数据库中的电子邮件列上添加唯一约束。
Assuming you're using a database for storage, you should definitely add a unique constraint on the e-mail column in the database.
查看有关 Simple Talk 的这篇优秀文章:
您应该避免的五个简单数据库设计错误
请参阅第 4 节:
因此,在您的情况下 - 您的电子邮件列的唯一约束实际上应该在数据库中建模。这是放置该业务逻辑的最佳位置,从长远来看,它将帮助您避免很多痛苦。
马克
Check out this excellent article on Simple Talk:
Five Simple Database Design Errors You Should Avoid
See in Section 4:
So in your case - a unique constraint on your e-mail column should really be modelled in the database. That's the best place to put that piece of business logic, and will save you from a lot of grief in the long run.
Marc