public int EditRecipe(RecipeVM recipe) { var entity = _db.Recipes .Include(r => r.Category) .FirstOrDefault(rcp => rcp.RecipeId == recipe.RecipeId); // edit existing entity if (entity == null) { entity = new Recipe(); } //_db.Recipes.Update(entity); //REMOVE existing values from lists var recipeIngredients = _db.Ingredients.Where(i => i.RecipeId == entity.RecipeId).ToList(); _db.Ingredients.RemoveRange(recipeIngredients); var methodItems = _db.MethodItems.Where(i => i.RecipeId == entity.RecipeId).ToList(); _db.MethodItems.RemoveRange(methodItems); //foreach (var ingredient in entity.Ingredients.ToList()) //{ // _db.Ingredients.Remove(ingredient); //} //foreach (var methodItem in entity.MethodItems.ToList()) //{ // _db.MethodItems.Remove(methodItem); //} _db.SaveChanges(); _mapper.Map(recipe, entity); entity.Category = _db.Categories.FirstOrDefault(c => c.CategoryId == recipe.CategoryId); entity.CategoryId = recipe.CategoryId; entity.Ingredients = new List <Ingredient>(); entity.MethodItems = new List <MethodItem>(); for (int i = 0; i < recipe.Ingredients.ToList().Count; i++) { var currentIngredient = recipe.Ingredients[i]; if (!string.IsNullOrEmpty(currentIngredient.Name)) { var ingredient = new Ingredient(); ingredient.Name = currentIngredient.Name; ingredient.Measure = currentIngredient.Measure; ingredient.Quantity = currentIngredient.Quantity; ingredient.PositionNo = i + 1; ingredient.RecipeId = entity.RecipeId; ingredient.Seperator = currentIngredient.Seperator; _db.Ingredients.Add(ingredient); } } for (int i = 0; i < recipe.MethodItems.Count; i++) { var currentMethodItem = recipe.MethodItems[i]; if (!string.IsNullOrEmpty(currentMethodItem.Text)) { var methodItem = new MethodItem(); methodItem.Text = currentMethodItem.Text; methodItem.StepNo = i + 1; methodItem.RecipeId = entity.RecipeId; methodItem.Seperator = currentMethodItem.Seperator; _db.MethodItems.Add(methodItem); } } // remove the existing image file from Azure if (entity.ImageUrl != null) { _azureBlobService.DeleteByNameAsync(entity.ImageUrl, imageContainerName); } // trim file to convert to base64 if (!string.IsNullOrEmpty(recipe.ImageFile)) { var base64 = recipe.ImageFile.Substring(recipe.ImageFile.LastIndexOf(',') + 1); byte[] imageBytes = Convert.FromBase64String(base64); using (var stream = new MemoryStream(imageBytes)) { IFormFile file = new FormFile(stream, 0, imageBytes.Length, "", ""); var fileNameTask = _azureBlobService.UploadSingleAsync(file, imageContainerName); entity.ImageUrl = fileNameTask.Result; } } //_db.Recipes.Update(entity); _db.SaveChanges(); return(entity.RecipeId); }