コード例 #1
0
        public async Task <IActionResult> Create(int PizzaId, List <int> NewIngredients)
        {
            if (ModelState.IsValid)
            {
                var                    oldIngredients       = _context.PizzaIngredients.Where(m => m.PizzaId == PizzaId).Select(m => m.IngredientId).ToList();
                List <int>             deleteIngredientsIds = oldIngredients.Except(NewIngredients).ToList();
                List <PizzaIngredient> toDelete             = _context.PizzaIngredients.Where(m => m.PizzaId == PizzaId && deleteIngredientsIds.Contains(m.IngredientId)).ToList();
                List <int>             addIngredientsIds    = NewIngredients.Except(oldIngredients).ToList();
                List <PizzaIngredient> toAdd = new List <PizzaIngredient>();
                foreach (int i in addIngredientsIds)
                {
                    toAdd.Add(new PizzaIngredient {
                        PizzaId = PizzaId, IngredientId = i
                    });
                }

                _context.RemoveRange(toDelete);
                _context.AddRange(toAdd);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", "Pizzas"));
            }
            ViewData["PizzaId"] = new SelectList(_context.Pizzas.Where(x => x.Id == PizzaId), "Id", "Name");
            return(View());
        }