实体框架:如何在提交之前检查值是否存在 [英] Entity Framework: How to check if value exists before submitting
问题描述
我正在使用存储库模式。
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).
推荐答案
由于多用户并发,您不能 SELECT
然后 INSERT
并保证没有问题。因此,@ Coding Gorilla提出的解决方案在高并发情况下可能会失败。
Because of multi-user concurrency, you can't SELECT
then INSERT
and be guaranteed of no problems. So the solution proposed by @Coding Gorilla could fail in high concurrency situations.
您应该在 UNIQUE
索引上放置相应的数据库列,并处理(或显示)如果国家/地区存在,您将获得的数据库异常。是的,您可以在服务层中执行此操作。这只是一个数据库调用,它将永远不会失败,因为数据库服务器可以保护您免受并发问题的影响。
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.
这篇关于实体框架:如何在提交之前检查值是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!