public async Task AddReview(ReviewDTO newReview) { using (var context = getContext()) { try { context.Reviews.Add(_translator.DtoToEntity(newReview)); await context.SaveChangesAsync(); } catch (DbUpdateException ex) { //If exception was caused by Foriegn Key Constraints or Unique Constraints // throw validation exception that will be proccessed to an HTTPResponse with clear failure reason in Abstract Controller if (!await context.Users.AnyAsync(u => u.Id == newReview.UserId)) { throw new ValidationException(String.Format("User with id {0} does not exist", newReview.UserId), ex); } if (!await context.Restaurants.AnyAsync(r => r.Id == newReview.RestaurantId)) { throw new ValidationException(String.Format("Restaurant with id {0} does not exist", newReview.RestaurantId), ex); } if (await context.Reviews.AnyAsync(r => r.RestaurantId == newReview.RestaurantId && r.UserId == newReview.UserId)) { throw new ValidationException(String.Format("User already wrote a review for this resturaunt. Delete it before adding new review.")); } throw; } } }
public async Task AddRestaruantAsync(RestaurantDTO newRestaurant) { using (var context = getContext()) { try { context.Restaurants.Add(_translator.DtoToEntity(newRestaurant)); await context.SaveChangesAsync(); } catch (DbUpdateException ex) { //If exception was caused by Foriegn Key Constraints or Unique Constraints // throw validation exception that will be proccessed to an HTTPResponse with clear failure reason in Abstract Controller if (!await context.Cities.AnyAsync(c => c.Id == newRestaurant.CityId)) { throw new ValidationException(String.Format("City with id {0} does not exists", newRestaurant.CityId), ex); } if (await context.Restaurants.AnyAsync(r => r.Name == newRestaurant.Name && r.Address == newRestaurant.Address)) { throw new ValidationException(String.Format("Restaurant with name, {0}, and address, {1}, already exists", newRestaurant.Name, newRestaurant.Address), ex); } throw; } } }