Entity Framework: How to check if value exists before submitting

廉价感情. 提交于 2019-12-01 14:01:28

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.

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