public async void PostRecipes_ReturnRecipes_WhenExistsInDB(string url)
        {
            //Act
            Utilities.InitializeUserAndCatagoryTestData(Context);
            Utilities.InitializeIngredientTestData(Context);
            RecipesRespondModel testRespondModel = new RecipesRespondModel()
            {
                Ingredients = new Dictionary <string, string>()
                {
                    { "milk", "1l" },
                    { "egg", "3" }
                },
                Category    = Utilities.CatagoryTypes.dessert.ToString(),
                Title       = "Test_Recipe_1",
                Description = "This is a Test value",
                Owner       = "testUser"
            };

            var stringRecipes = await Task.Run(() => JsonConvert.SerializeObject(testRespondModel));

            var httpContent  = new StringContent(stringRecipes, Encoding.UTF8, "application/json");
            var postResponse = await Client.PostAsync(url, httpContent);

            //Assert
            postResponse.StatusCode.Should().Be(HttpStatusCode.Created);

            var getResponse = await Client.GetAsync(url);

            getResponse.StatusCode.Should().Be(HttpStatusCode.OK);
            (await getResponse.Content.ReadAsAsync <List <RecipesRespondModel> >()).Should().HaveCount(1);
        }
        public async Task <IActionResult> UpdateRecipe([FromRoute] int id, [FromBody] RecipesRespondModel recipeRespondModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (string.IsNullOrEmpty(recipeRespondModel.Title))
            {
                return(BadRequest("Invalid Title"));
            }

            var recipe = await _context.Recipes.FindAsync(id);

            recipe.Title       = recipeRespondModel.Title;
            recipe.Catagory    = _context.Catagories.First(a => recipeRespondModel != null && a.Name.ToLower().Equals(recipeRespondModel.Category.ToLower()));
            recipe.Description = recipeRespondModel.Description;


            // delete IngredientInfoes
            DeleteRelevantIngredentInfosDetails(id);

            var recipeIngredentsInfo = new List <IngredientInfo>();

            foreach (var kvp in recipeRespondModel.Ingredients)
            {
                var ingredient     = _context.Ingredients.FirstOrDefault(a => a.Title.ToLower().Equals(kvp.Key.ToLower()));
                var ingredientInfo = new IngredientInfo()
                {
                    Ingredient = ingredient, Qty = kvp.Value, Recipe = recipe
                };
                recipeIngredentsInfo.Add(ingredientInfo);
            }

            recipe.IngredientInfoes = recipeIngredentsInfo;
            await _context.IngredientInfoes.AddRangeAsync(recipeIngredentsInfo);

            ///
            ///
            _context.Entry(recipe).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RecipeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <IActionResult> SaveRecipe([FromBody] RecipesRespondModel recipeRespondModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = _context.Users.FirstOrDefault(a => a.UserName.Equals(recipeRespondModel.Owner));

            if (user == null)
            {
                return(BadRequest($"Invalid User {recipeRespondModel.Owner}"));
            }

            var category = _context.Catagories.FirstOrDefault(a => a.Name.Trim().ToLower().Equals(recipeRespondModel.Category.Trim().ToLower()));

            if (category == null)
            {
                return(BadRequest($"Invalid Catagory {recipeRespondModel.Category}"));
            }

            var recipe = new Recipe()
            {
                Title       = recipeRespondModel.Title,
                Description = recipeRespondModel.Description,
                Catagory    = category,
                User        = user,
            };

            foreach (var kvp in recipeRespondModel.Ingredients)
            {
                var ingredient     = _context.Ingredients.FirstOrDefault(a => a.Title.ToLower().Equals(kvp.Key.ToLower()));
                var ingredientInfo = new IngredientInfo()
                {
                    Ingredient = ingredient, Qty = kvp.Value, Recipe = recipe
                };
                recipe.IngredientInfoes.Add(ingredientInfo);
                await _context.IngredientInfoes.AddAsync(ingredientInfo);
            }

            await _context.Recipes.AddAsync(recipe);

            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetRecipeByID", new { id = recipe.RecipeId }, recipeRespondModel));
        }
        private RecipesRespondModel InitializeRecipesRespondModel(Recipe recipe)
        {
            var recipeModel = new RecipesRespondModel
            {
                Id          = recipe.RecipeId,
                Title       = recipe.Title,
                Description = recipe.Description,
                Category    = _context.Catagories.First(a => a.CatagoryId.Equals(recipe.CatagoryId)).Name,
                Owner       = _context.Users.First(a => a.UserId.Equals(recipe.UserId)).UserName
            };
            var queryable = _context.IngredientInfoes.Where(a => a.RecipeId.Equals(recipe.RecipeId))
                            .Select(a => new { a.IngredientId, a.Qty });

            foreach (var kvp in queryable)
            {
                recipeModel.Ingredients[_context.Ingredients.First(a => a.IngredientId.Equals(kvp.IngredientId)).Title] = kvp.Qty;
            }
            return(recipeModel);
        }
        public async void UpdateRecipes_WhenExistsInDB(string url)
        {
            //Act
            Utilities.InitializeUserAndCatagoryTestData(Context);
            Utilities.InitializeIngredientTestData(Context);
            RecipesRespondModel testRespondModel = new RecipesRespondModel()
            {
                Ingredients = new Dictionary <string, string>()
                {
                    { "milk", "1l" },
                    { "egg", "3" }
                },
                Category    = Utilities.CatagoryTypes.dessert.ToString(),
                Title       = "Test_Recipe_1",
                Description = "This is a Test value",
                Owner       = "testUser"
            };

            var stringRecipes = await Task.Run(() => JsonConvert.SerializeObject(testRespondModel));

            var httpContent  = new StringContent(stringRecipes, Encoding.UTF8, "application/json");
            var postResponse = await Client.PostAsync(url, httpContent);

            //Assert
            postResponse.StatusCode.Should().Be(HttpStatusCode.Created);

            var getResponse = await Client.GetAsync($"{url}/1");

            getResponse.StatusCode.Should().Be(HttpStatusCode.OK);
            var existingItem = JsonConvert.DeserializeObject <RecipesRespondModel>(await getResponse.Content.ReadAsStringAsync());

            existingItem.Title       = "Test_Recipe_Edit";
            existingItem.Description = "This is edit value";
            existingItem.Category    = Utilities.CatagoryTypes.starters.ToString();
            existingItem.Ingredients = new Dictionary <string, string>()
            {
                { "milk", "5l" },
                { "egg", "10" }
            };

            stringRecipes = await Task.Run(() => JsonConvert.SerializeObject(existingItem));

            httpContent = new StringContent(stringRecipes, Encoding.UTF8, "application/json");

            var putResponse = await Client.PutAsync($"{url}/1", httpContent);

            putResponse.StatusCode.Should().Be(HttpStatusCode.NoContent);

            getResponse = await Client.GetAsync($"{url}/1");

            getResponse.StatusCode.Should().Be(HttpStatusCode.OK);
            existingItem = JsonConvert.DeserializeObject <RecipesRespondModel>(await getResponse.Content.ReadAsStringAsync());

            Assert.Equal("Test_Recipe_Edit", existingItem.Title);
            Assert.Equal("This is edit value", existingItem.Description);
            Assert.Equal(Utilities.CatagoryTypes.starters.ToString(), existingItem.Category);
            Assert.True(existingItem.Ingredients.Keys.Contains("milk"));
            Assert.True(existingItem.Ingredients.Keys.Contains("egg"));
            Assert.Equal("5l", existingItem.Ingredients["milk"]);
            Assert.Equal("10", existingItem.Ingredients["egg"]);
        }