// POST: api/Customers public IHttpActionResult Post([FromBody] CustomerAdd newItem) { // Ensure that the URI is clean (and does not have an id parameter) if (Request.GetRouteData().Values["id"] != null) { return(BadRequest("Invalid request URI")); } // Ensure that a "newItem" is in the entity body if (newItem == null) { return(BadRequest("Must send an entity body with the request")); } // Ensure that we can use the incoming data if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Attempt to add the new object var addedItem = m.CustomerAdd(newItem); // Continue? if (addedItem == null) { return(BadRequest("Cannot add the object")); } // HTTP 201 with the new object in the entity body // Notice how to create the URI for the Location header var uri = Url.Link("DefaultApi", new { id = addedItem.CustomerId }); return(Created(uri, addedItem)); }
// Attention 27 - Customer add one public CustomerBase CustomerAdd(CustomerAdd newItem) { // Attention 28 - To add a customer, we MUST have an Employee identifier // We must validate that employee first by attempting to fetch it // If successful, then we can continue // Attempt to find the associated object var a = ds.Employees.Find(newItem.SupportRepId); if (a == null) { return(null); } else { // Attempt to add the object var addedItem = ds.Customers.Add(Mapper.Map <Customer>(newItem)); // Set the associated item property addedItem.Employee = a; ds.SaveChanges(); // Return the result, or null if there was an error return((addedItem == null) ? null : Mapper.Map <CustomerBase>(addedItem)); } }