public IActionResult Create([FromBody] ProductToCreateViewModel model)
        {
            if (model == null)
            {
                return(BadRequest());
            }

            if (ModelState.IsValid)
            {
                var productEntity = Mapper.Map <Product>(model);
                _productsRepository.Create(productEntity);

                if (!_productsRepository.Save())
                {
                    throw new Exception("Creating a product failed on save.");
                }

                var productToReturn = Mapper.Map <Product>(productEntity);

                return(CreatedAtRoute("GetProduct", new { id = productToReturn.Id }, productToReturn));
            }

            // return 422 - !ModelState.IsValid
            return(new UnprocessableModelStateObjectResult(ModelState));
        }
Example #2
0
        public async Task <IActionResult> Add([FromBody] ProductToCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    //Init product object
                    var newProduct = _mapper.Map <Product>(model);
                    newProduct.CreatedDate = DateTime.Now;

                    //Adding new object to database
                    await _context.Products.AddAsync(newProduct);

                    await _context.SaveChangesAsync();

                    if (newProduct.ProductId > 0)
                    {
                        return(Ok(newProduct.ProductId));
                    }
                    else
                    {
                        return(NotFound());
                    }
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex));
                }
            }

            return(BadRequest());
        }