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