开发者

Entity Framework: How to check if value exists before submitting

开发者 https://www.devze.com 2023-01-31 16:55 出处:网络
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 al开发者_开发知识库ready exists in the database,

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 al开发者_开发知识库ready 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).


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);
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消