/// <summary> /// Support for updating products /// </summary> public async Task<IHttpActionResult> Put([FromODataUri] int key, Product update) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (key != update.ID) { return BadRequest(); } _db.Entry(update).State = EntityState.Modified; try { await _db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!_db.Products.Any(p => p.ID == key)) { return NotFound(); } else { throw; } } return Updated(update); }
/// <summary> /// Support for creating products /// </summary> public async Task<IHttpActionResult> Post(Product product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _db.Products.Add(product); await _db.SaveChangesAsync(); return Created(product); }
/// <summary> /// Support for updating products /// </summary> public HttpResponseMessage Put([FromODataUri] int key, Product update) { if (!_db.Products.Any(p => p.ID == key)) { throw ODataErrors.EntityNotFound(Request); } update.ID = key; // ignore the key in the entity use the key in the URL. _db.Products.Attach(update); _db.Entry(update).State = EntityState.Modified; _db.SaveChanges(); return Request.CreateResponse(HttpStatusCode.NoContent); }
/// <summary> /// Support for creating products /// </summary> public HttpResponseMessage Post(Product product) { product.Family = null; Product addedProduct = _db.Products.Add(product); _db.SaveChanges(); var response = Request.CreateResponse(HttpStatusCode.Created, addedProduct); var odataPath = Request.GetODataPath(); if (odataPath == null) { throw new InvalidOperationException("There is no ODataPath in the request."); } var entitySetPathSegment = odataPath.Segments.FirstOrDefault() as EntitySetPathSegment; if (entitySetPathSegment == null) { throw new InvalidOperationException("ODataPath doesn't start with EntitySetPathSegment."); } response.Headers.Location = new Uri(Url.ODataLink( entitySetPathSegment, new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(addedProduct.ID, ODataVersion.V3)))); return response; }
public async Task<IHttpActionResult> CreateProduct([FromODataUri] int key, ODataActionParameters parameters) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var productFamily = await _db.ProductFamilies.FindAsync(key); var productName = parameters["Name"].ToString(); var product = new Product { Name = productName, Family = productFamily, ReleaseDate = DateTime.Now, SupportedUntil = DateTime.Now.AddYears(10) }; _db.Products.Add(product); await _db.SaveChangesAsync(); return Ok(product.Id); }
/// <summary> /// Support for POST /ProductFamiles(1)/Products /// </summary> public async Task<IHttpActionResult> PostToProducts([FromODataUri] int key, Product product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var family = await _db.ProductFamilies.FindAsync(key); if (family == null) { return NotFound(); } family.Products.Add(product); await _db.SaveChangesAsync(); return Created(product); }