Entity Framework: How to check if value exists before submitting

不打扰是莪最后的温柔 提交于 2019-12-01 13:36:00

问题


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).


回答1:


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.

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.




回答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?

public void InsertIfNonExistant(string Country)
{
   if(!_myContext.Countries.Any(c=>c.Name == Country))
      InsertNewCountry(Country);
}


来源:https://stackoverflow.com/questions/4473576/entity-framework-how-to-check-if-value-exists-before-submitting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!