In my C# project I have a method that ask if an object exists in the db and if not then creates it. Now, if two users asks the same question simultaneously they both get null so the flow will be to save to db which is impossible for two duplicates to do that, so will raise an sql exception. How can I deal with this issue please?
here is my code:
var date = DateTime.UtcNow.Date;
var todayCelebPageView = _celebPageViewsRepo.GetAll().SingleOrDefault(d => d.iCelebId == celebId && d.dDate == date);
if (todayCelebPageView != null)
{
todayCelebPageView.iScore++;
_celebPageViewsRepo.Save();
}
else
{
todayCelebPageView = new MovliCelebPageView() {dDate = date, iCelebId = celebId, iScore = 1};
_celebPageViewsRepo.Add(todayCelebPageView);
_movliRepository.DbContext.Entry(todayCelebPageView).State = System.Data.EntityState.Added;
_celebPageViewsRepo.Save();
}
Theres no easy answer to this really, it's a common problem with a number of solutions.
Some options might be:
Something else to consider is what should happen from a business point of view when two attempts are made to create a record at the same time.
Should the person who created the record last win? Should the first person win and the second receive an error? Or should you write the first record and update it again with the second?
The answer to this will depend entirely on the specifics of what you are trying to do in your application.