Example #1
0
        public async Task <IActionResult> Post([FromBody] OrderViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newOrder = _mapper.Map <OrderViewModel, Order>(model);

                    if (newOrder.OrderDate == DateTime.MinValue)
                    {
                        newOrder.OrderDate = DateTime.Now;
                    }

                    var currentUser = await _userManager.FindByNameAsync(User.Identity.Name);

                    newOrder.User = currentUser;

                    _repository.AddOrder(newOrder);
                    if (_repository.SaveAll())
                    {
                        var vm = new OrderViewModel()
                        {
                            OrderId     = newOrder.Id,
                            OrderDate   = newOrder.OrderDate,
                            OrderNumber = newOrder.OrderNumber
                        };
                        return(Created($"api/order/{newOrder.Id}", _mapper.Map <Order,
                                                                                OrderViewModel>(newOrder)));
                    }
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to post order {ex}");
            }
            return(BadRequest("Failed to save new order."));
        }