实体框架:如何在提交之前检查值是否存在
我正在使用存储库模式。
我有一个国家/地区存储库,我正在使用服务来提交该存储库。我应该在哪里检查该国家/地区是否已存在于数据库中,我会抛出异常吗?
有没有一种方法可以在一次数据库调用中做到这一点? (如果不存在则检查并插入)?如果可以的话可以在服务层实现吗? (如果这是您建议我进行检查的地方)。
I'm using the repository pattern.
I have a Country repository that I'm using a service to submit. Where should I put the check to see if the country already exists in the database, I throw an exception?
Is there a way to do this in one database call? (Check and insert if non-existent)? If this is possible, could it be done in the service layer? (if that is where you recommend I do the checks).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是否将这种逻辑放入您的服务或存储库中是一个主观问题。就我个人而言,我会让服务检查并插入(如果它不存在),但也会让您的存储库在尝试插入之前验证它不存在,这样您的存储库就会强制执行一些“逻辑”来阻止您的数据库免于被骗。
怎么做呢?
Whether to put this kind of logic in your service or your repository is a bit of a subjective question. Personally I would make the service check and insert if it doesn't exist, but then also make your repository validate that it doesn't exist before attempting to do the insert, that way your repository is enforcing some "logic" to prevent your database from getting full of dupes.
How to do it?
由于多用户并发,您无法先
SELECT
然后INSERT
并保证不会出现任何问题。所以@Coding Gorilla提出的解决方案在高并发情况下可能会失败。您应该在适当的数据库列上放置一个
UNIQUE
索引,并处理(或显示)如果该国家/地区存在的话您将获得的数据库异常。是的,您可以在服务层中执行此操作。这只是一次数据库调用,并且永远不会失败,因为数据库服务器会保护您免受并发问题的影响。Because of multi-user concurrency, you can't
SELECT
thenINSERT
and be guaranteed of no problems. So the solution proposed by @Coding Gorilla could fail in high concurrency situations.You should put a
UNIQUE
index on the appropriate DB columns and handle (or let surface) the DB exception you'll get if the country exists. Yes, you can do this in the service layer. This is only one DB call and it will never fail, as the DB server protects you from the concurrency issue.