コード例 #1
0
        public async Task AddAsync(string name, string imageURL, List <CocktailIngredientDTO> ingredientsAndQuantities)
        {
            //TODO To ask if it is neccessary double protection against invalid input

            if (ingredientsAndQuantities == null || ingredientsAndQuantities.Count() == 0)
            {
                throw new InvalidOperationException(OutputConstants.CocktailWithNoIngredients);
            }

            if (ingredientsAndQuantities.Any(i => i.Value == 0.0))
            {
                throw new InvalidOperationException(OutputConstants.NoIngredientQuantity);
            }

            if (context.Cocktails.Any(c => c.Name == name && c.IsDeleted == false))
            {
                throw new ArgumentException(OutputConstants.CocktailExists);
            }


            var cocktail = cocktailFactory.Create(name, imageURL);

            foreach (var ingredient in ingredientsAndQuantities)
            {
                var ingrId = await context.Ingredients.Where(i => i.Name == ingredient.Name).Select(i => i.Id).FirstOrDefaultAsync();

                var cocktailIngredient = cocktailIngredientFactory.Create(cocktail, ingrId, ingredient.Value);
                context.CocktailIngredients.Add(cocktailIngredient);
            }
            await context.SaveChangesAsync();
        }