public bool CategoryExists(Category category) { bool result = _context.Categories .AsNoTracking() .Where(cat => cat.IsActive == true) .SingleOrDefault(cat => cat.Name.Equals(category.Name, StringComparison.InvariantCultureIgnoreCase)) != null; return result; }
public bool DuplicateNameExists(Category category) { var possibleDuplicates = _context.Categories .AsNoTracking() .Where(cat => cat.IsActive == true && cat.Name.Equals(category.Name, StringComparison.InvariantCultureIgnoreCase) && cat.Id != category.Id); bool result = possibleDuplicates.Count() > 0; return result; }
public ActionResult Create(CategoryViewModel model) { if (ModelState.IsValid) { Category newCat = new Category() { Name = model.Name }; if (_itemsRepository.CategoryExists(newCat)) { ModelState.AddModelError("", "A category with this name already exists"); return View(); } _itemsRepository.AddCategory(newCat); _itemsRepository.Save(); return RedirectToAction("Index"); } //return for the user to fix the errors if we got to here return View(); }
public Category GetCategory(int id) { Category cat = GetSingleActiveCategoryOrNull(id); if (cat == null) { return null; } else { Category catWithoutInactive = new Category() { Id = cat.Id, Name = cat.Name, Products = cat.Products.Where(p => p.IsActive == true).ToArray() }; return catWithoutInactive; } }
public void AddCategory(Category category) { category.IsActive = true; _context.Categories.Add(category); }
public void UpdateCategory(Category category) { Category cat = GetSingleActiveCategoryOrNull(category.Id); if (cat != null) { cat.Name = category.Name; cat.Products = category.Products; } else { throw new InvalidOperationException("The category for edit does not exist or can not be used"); } }
public ActionResult Edit(CategoryViewModel model) { if (ModelState.IsValid) { Category editedCat = new Category() { Id = model.Id, Name = model.Name }; if (_itemsRepository.DuplicateNameExists(editedCat)) { ModelState.AddModelError("", "A category with this name already exists."); return View(model); } _itemsRepository.UpdateCategory(editedCat); _itemsRepository.Save(); return RedirectToAction("Index"); } //return to the user to fix the errors return View(model); }