public IActionResult CreateProduct([FromBody] ProductForCreationDTO product)
        {
            if (product == null)
            {
                return(BadRequest());
            }

            // Validate data
            if (!ModelState.IsValid)
            {
                // return 422
                return(new UnprocessableEntityObjectResult(ModelState));
            }

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

            _supermarketRepository.AddProduct(productEntity);

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

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

            var links = CreateLinksForProduct(productToReturn.ProductId, null);

            var linkedResourceToReturn = productToReturn.ShapeData(null)
                                         as IDictionary <string, object>;

            linkedResourceToReturn.Add("links", links);

            return(CreatedAtRoute("GetProduct", new { ProductId = linkedResourceToReturn["ProductId"] }, linkedResourceToReturn));
        }
Exemple #2
0
        public IActionResult CreateProductCollection([FromBody] IEnumerable <ProductForCreationDTO> productCollection)
        {
            if (productCollection == null)
            {
                return(BadRequest());
            }

            // Validate data
            foreach (ProductForCreationDTO p in productCollection)
            {
                if (!ModelState.IsValid)
                {
                    // return 422
                    return(new UnprocessableEntityObjectResult(ModelState));
                }
            }

            var productEntities = Mapper.Map <IEnumerable <Product> >(productCollection);

            foreach (var product in productEntities)
            {
                _supermarketRepository.AddProduct(product);
            }

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

            var productCollectionToReturn = Mapper.Map <IEnumerable <ProductDTO> >(productEntities);
            var idsAsString = string.Join(",", productCollectionToReturn.Select(p => p.ProductId));

            return(CreatedAtRoute("GetProductCollection",
                                  new { ids = idsAsString },
                                  productCollectionToReturn));
        }