Ejemplo n.º 1
0
        public IActionResult CreateProduct([FromBody] ProductForCreationDto product)
        {
            if (product == null)
            {
                return(BadRequest());
            }

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

            _libraryRepository.AddProduct(productEntity);

            if (!_libraryRepository.Save())
            {
                throw new Exception("Creating a product failed on save.");
                //return StatusCode(500, "An unexpected fault happened. Try again later.");
            }

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

            return(CreatedAtRoute("GetProduct", new { id = productToReturn.Id }, productToReturn));
        }
        public IActionResult CreateProductCollection([FromBody] IEnumerable <ProductForCreationDto> productCollection)
        {
            if (productCollection == null)
            {
                return(BadRequest());
            }

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

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

            if (!_libraryRepository.Save())
            {
                throw new Exception("An error occur while saving a collection of product");
            }

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

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