public RepositoryActionResult<ProductCategory> AddProductCategory(ProductCategory newProductCategory) { try { //Adds new product category _ctx.ProductCategories.Add(newProductCategory); //Saves Changes var result = _ctx.SaveChanges(); //Returns Product Category & Status if (result > 0) { return new RepositoryActionResult<ProductCategory>(newProductCategory, RepositoryActionStatus.Created); } else { return new RepositoryActionResult<ProductCategory>(newProductCategory, RepositoryActionStatus.NothingModified, null); } } catch (Exception ex) { return new RepositoryActionResult<ProductCategory>(null, RepositoryActionStatus.Error, ex); } }
public RepositoryActionResult<ProductCategory> UpdateProductCategory(ProductCategory updatedProductCategory) { try { // Only update when product category already exists var existingProduct = _ctx.Products.FirstOrDefault(b => b.Id == updatedProductCategory.Id); if (existingProduct == null) { return new RepositoryActionResult<ProductCategory>(updatedProductCategory, RepositoryActionStatus.NotFound); } // Change the original entity status to detached; otherwise, we get an error on attach // as the entity is already in the dbSet // set original entity state to detached _ctx.Entry(existingProduct).State = EntityState.Detached; // attach & save _ctx.ProductCategories.Attach(updatedProductCategory); // set the updated entity state to modified, so it gets updated. _ctx.Entry(updatedProductCategory).State = EntityState.Modified; // Save Changes var result = _ctx.SaveChanges(); //Returns Book & Status if (result > 0) { return new RepositoryActionResult<ProductCategory>(updatedProductCategory, RepositoryActionStatus.Updated); } else { return new RepositoryActionResult<ProductCategory>(updatedProductCategory, RepositoryActionStatus.NothingModified, null); } } catch (Exception ex) { return new RepositoryActionResult<ProductCategory>(null, RepositoryActionStatus.Error, ex); } }