public async Task <ActionResult <OrderModel> > Post(OrderModel model) { try { var existingOrder = await _repository.GetOrderAsync(model.OrderNumber); if (existingOrder != null) { return(BadRequest("Order in Use")); } var location = _linkGenerator.GetPathByAction("Get", "Orders", new { orderNumber = model.OrderNumber }); if (string.IsNullOrWhiteSpace(location)) { return(BadRequest("Could not use current orderNumber")); } // create new order var order = _mapper.Map <Order>(model); _repository.Add(order); if (await _repository.SaveChangesAsync()) { return(Created($"/api/orders/{order.OrderNumber}", _mapper.Map <OrderModel>(order))); } } catch (Exception) { return(this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure")); } return(BadRequest()); }
public async Task <ActionResult <OrderItemModel> > Post(string orderNumber, OrderItemModel model) { try { var order = await _repository.GetOrderAsync(orderNumber); if (order == null) { return(BadRequest("Order does not exist")); } var orderItem = _mapper.Map <OrderItem>(model); orderItem.Order = order; if (model.Book == null) { return(BadRequest("Book ID is required")); } var book = await _repository.GetBookAsync(model.Book.BookId); if (book == null) { return(BadRequest("Book could not be found")); } orderItem.Book = book; _repository.Add(orderItem); if (await _repository.SaveChangesAsync()) { var url = _linkGenerator.GetPathByAction(HttpContext, "Get", values: new { orderNumber, id = orderItem.OrderItemId }); return(Created(url, _mapper.Map <OrderItemModel>(orderItem))); } else { return(BadRequest("Failed to save new orderItem")); } } catch (Exception) { return(StatusCode(StatusCodes.Status500InternalServerError, "Failed to post OrderItem")); } }