public bool Add(Product product) { var toInsert = new ProductEntity() { IntroductionDate = product.IntroductionDate, Price = product.Price, ProductId = product.ProductId, ProductName = product.ProductName, Url = product.Url, Summary = product.Summary }; _dbProducts.Products.Add(toInsert); var changesMade = _dbProducts.SaveChanges(); return (changesMade >= 1); }
public bool Update(Product product) { var id = product.ProductId; using (var db = new EfProducts()) { var fromDb = db.Products.Find(id); fromDb.IntroductionDate = product.IntroductionDate; fromDb.Price = product.Price; fromDb.ProductId = id; fromDb.ProductName = product.ProductName; fromDb.Url = product.Url; fromDb.Summary = product.Summary; return db.SaveChanges() >= 1; } }
protected bool Validate(Product product) { bool ret = false; // add custom validation if (product.IntroductionDate < Convert.ToDateTime("1/1/2010")) { ModelState.AddModelError("Introduction Date", "Introduction Date Must Be Greater Than 1/1/2010"); } // Add more server-side validation here to match // or if using DataAnnotations (like with Entity Objects), you can retrieve the ModelState (Dictionary) object, //get the errors from the annotations and add those to the ValidationErrors collection property. ValidationErrors = ModelState; return ModelState.IsValid; ret = (ValidationErrors.Count == 0); return ret; }
public IHttpActionResult Put(int id, Product product) { IHttpActionResult ret = null; if (Validate(product)) { if (_repo.Exists(id)) { if (_repo.Update(product)) { ret = Ok(product); } else { ret = InternalServerError(); } } else { ret = NotFound(); } } else { ret = BadRequest(ValidationErrors); } return ret; }
public IHttpActionResult Post(Product product) { IHttpActionResult ret = null; if (Validate(product)) { if (_repo.Add(product)) { // get the id that we just created. var newRecId = _repo.GetAll() .First(x => x.ProductName == product.ProductName && x.Price == product.Price && x.IntroductionDate == product.IntroductionDate && x.Url == product.Url).ProductId; product.ProductId = newRecId; ret = Created<Product>(Request.RequestUri + product.ProductId.ToString(), product); } else { ret = InternalServerError(); } } else { ret = BadRequest(ValidationErrors); } return ret; }
public IHttpActionResult Get(int id) { IHttpActionResult toReturn = null; Product prod = new Product(); var ent = _repo.GetAll().FirstOrDefault(x => x.ProductId == id); if (ent != null) { prod.Price = ent.Price.Value; prod.IntroductionDate = ent.IntroductionDate.Value; prod.Url = ent.Url; prod.ProductName = ent.ProductName; prod.ProductId = ent.ProductId; prod.Summary = ent.Summary; toReturn = Ok(prod); } else { toReturn = NotFound(); } return toReturn; }