// Attention 31 - Customer edit address, returns extra data // Must do a bit more than a normal "edit existing", because of the association // One extra fetch before return so that the associated data comes back // Please be aware that there could be alternative coding plans - // the following plan is not authoritative, and others could work public CustomerWithData CustomerEditAddress(CustomerEditAddress editedItem) { // Ensure that we can continue if (editedItem == null) { return(null); } // Attempt to fetch the object var storedItem = ds.Customers.Find(editedItem.CustomerId); if (storedItem == null) { return(null); } else { // Fetch the object from the data store - ds.Entry(storedItem) // Get its current values collection - .CurrentValues // Set those to the edited values - .SetValues(editedItem) ds.Entry(storedItem).CurrentValues.SetValues(editedItem); // The SetValues() method ignores missing properties and navigation properties ds.SaveChanges(); // Extra fetch var o = ds.Customers.Include("Employee") .SingleOrDefault(c => c.CustomerId == storedItem.CustomerId); return(Mapper.Map <CustomerWithData>(o)); } }
// PUT: api/Customers/5 /// <summary> /// Edit customer address /// </summary> /// <param name="id">Customer identifier</param> /// <param name="editedItem">Address data</param> /// <returns>Customer object</returns> public IHttpActionResult Put(int?id, [FromBody] CustomerEditAddress editedItem) { // Ensure that an "editedItem" is in the entity body if (editedItem == null) { return(BadRequest("Must send an entity body with the request")); } // Ensure that the id value in the URI matches the id value in the entity body if (id.GetValueOrDefault() != editedItem.CustomerId) { return(BadRequest("Invalid data in the entity body")); } // Ensure that we can use the incoming data if (ModelState.IsValid) { // Attempt to update the item var changedItem = m.CustomerEditAddress(editedItem); // Notice the ApiController convenience methods if (changedItem == null) { // HTTP 400 return(BadRequest("Cannot edit the object")); } else { // Attention 32 - Edit address result, create a hypermedia representation CustomerLinked result = new CustomerLinked (Mapper.Map <CustomerWithLink>(changedItem)); // HTTP 200 with the changed item in the entity body return(Ok(result)); } } else { return(BadRequest(ModelState)); } }