Ejemplo n.º 1
0
        public IActionResult Create([FromBody] BookDto book)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newBook = _mapper.Map <BookDto, Book>(book);
                    _repository.AddEntity(newBook);


                    if (_repository.SaveAll())
                    {
                        return(CreatedAtAction(nameof(GetBook), new { id = book.Id }, _mapper.Map <Book, BookDto>(newBook)));
                    }
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"Failed to save a new book: {ex}");
            }

            return(BadRequest("Failed to save a new book"));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Post([FromBody] OrderDto model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newOrder = _mapper.Map <OrderDto, 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())
                    {
                        return(Created($"/api/Orders/{newOrder.Id}", _mapper.Map <Order, OrderDto>(newOrder)));
                    }
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"Failed to save a new order: {ex}");
            }

            return(BadRequest("Failed to save new order"));
        }