public CategoryReadVm CreateCategory(CategoryWriteVm newCategory) { // Create a new Category Domain Object var category = new Category() { Name = newCategory.Name }; // Associate any provided products category.Products = repo.Read <Product>().Where(x => newCategory.ProductIds.Contains(x.Id)).ToArray(); // Attach category to DB var item = repo.Create(category); return(new CategoryReadVm() { Id = item.Id, Name = item.Name, Products = item.Products.Select(p => new ProductReadVm() { Id = p.Id, Name = p.Name, Price = p.Price, InStock = p.InStock }) }); }
public IActionResult Post([FromBody] CategoryWriteVm newCategory) { // Exercise ModelState Validation if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var category = service.CreateCategory(newCategory); return(Created("api/categories" + category.Id, category)); }
public IActionResult Put([FromRoute] int id, [FromBody] CategoryWriteVm newCategory) { // Exercise ModelState Validation if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var category = service.UpdateCategory(id, newCategory); // Verify that the category was updated if (category == null) { return(NotFound()); } return(NoContent()); }
public CategoryReadVm UpdateCategory(int id, CategoryWriteVm newCategory) { // Get existing category from DB var category = repo.Read <Category>() .Include(x => x.Products) .FirstOrDefault(x => x.Id == id); // Verify that the category exist if (category == null) { return(null); } // Assign updated Properties category.Name = newCategory.Name; foreach (var product in repo.Read <Product>().Where(x => newCategory.ProductIds.Contains(x.Id))) { category.Products.Add(product); } foreach (var product in repo.Read <Product>().Where(x => newCategory.RemoveProductIds.Contains(x.Id))) { category.Products.Remove(product); } repo.Update(category); return(new CategoryReadVm() { Id = category.Id, Name = category.Name, Products = category.Products.Select(p => new ProductReadVm() { Id = p.Id, Name = p.Name, Price = p.Price, InStock = p.InStock }) }); }