/// <summary> /// Updates existing ingredient /// </summary> /// <param name="id">ID of the ingredient</param> /// <param name="ingredientDTO">The Ingredient DTO model with the new properties.</param> /// <returns>The updated ingredient, DTO</returns> public async Task <IngredientDTO> UpdateAsync(Guid id, IngredientDTO ingredientDTO) { var ingredient = await _context.Ingredients.FindAsync(id); if (ingredient == null) { return(null); } try { _context.Entry(ingredient).State = EntityState.Modified; ingredient.Name = ingredientDTO.Name; ingredient.IsAlcoholic = ingredientDTO.IsAlcoholic; _context.Update(ingredient); await _context.SaveChangesAsync(); } catch (Exception) { //TODO: think what to return and when? if (!IngredientExists(id)) { return(null); } else { throw new ArgumentException(); } } return(_mapper.MapEntityToDTO(ingredient)); }
/// <summary> /// Updates existing cocktail /// </summary> /// <param name="id">ID of the cocktail</param> /// <param name="cocktailDTO">The cocktail with the modifications</param> /// <returns>Cocktail DTO.model</returns> public async Task <CocktailDTO> UpdateAsync(Guid id, CocktailDTO cocktailDTO) { try { if (cocktailDTO == null) { throw new ArgumentNullException("Cocktail DTO to update is null."); } var cocktail = await _context.Cocktails.FindAsync(id); _context.Entry(cocktail).State = EntityState.Modified; //cocktail = this._mapper.MapDTOToEntity(cocktailDTO); cocktail.Id = cocktailDTO.Id; cocktail.Name = cocktailDTO.Name; cocktail.Rating = cocktailDTO.Rating; cocktail.TimesRated = cocktailDTO.TimesRated; cocktail.ImageSrc = cocktailDTO.ImageSrc; cocktail.IsDeleted = cocktailDTO.IsDeleted; cocktail.IsAlcoholic = cocktailDTO.IsAlcoholic; cocktail.Instructions = cocktailDTO.Instructions; //remove ingredients var previousIngredients = _context.CocktailIngredients .Where(i => i.CocktailId == cocktail.Id) .AsQueryable(); _context.CocktailIngredients.RemoveRange(previousIngredients); //add new ingredients foreach (var item in cocktailDTO.Ingredients) { if (item.IngredientId != Guid.Empty) { bool isAdded = await AddIngredientsToCocktail(cocktail, item.IngredientId, item.Parts); if (isAdded == false) { throw new OperationCanceledException("Adding cocktail ingredient failed."); } } } if (cocktail.Ingredients.Select(x => x.Ingredient).Any(i => i.IsAlcoholic)) { cocktail.IsAlcoholic = true; } else { cocktail.IsAlcoholic = false; } _context.Update(cocktail); await _context.SaveChangesAsync(); return(_mapper.MapEntityToDTO(cocktail)); } catch (Exception e) { throw new ArgumentNullException(); } }