Ejemplo n.º 1
0
        [HttpPost]              // Added by PW as preferred method. Microsoft suggest calling the function Post<ControllerName>
        public IHttpActionResult PostNewRental(NewRentalDto newRental)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (newRental.MovieIds.Count == 0)
            {
                return(BadRequest("No Movie IDs have been supplied"));
            }

            Customer customer = _customerRepository.GetById(newRental.CustomerId);

            if (customer == null)
            {
                return(BadRequest("Invalid customer ID supplied"));
            }


            // Get the movies where the movie ID is in the array of IDs supplied in the DTO
            var movies = db.Movies.Where(
                m => newRental.MovieIds.Contains(m.MovieId)).ToList();

            if (movies.Count != newRental.MovieIds.Count)
            {
                return(BadRequest("One or more movie IDs is incorrect."));
            }


            foreach (var movie in movies)
            {
                if (movie.NumberAvailable == 0)
                {
                    return(BadRequest("Movie is not available"));
                }

                var rental = new Rental();
                rental.CustomerId = newRental.CustomerId;
                rental.MovieId    = movie.MovieId;
                rental.DateRented = newRental.DateRented;

                _rentalRepository.Insert(rental);

                // Decrease the available number of this movie to rent
                movie.NumberAvailable--;    // Decrease the number available
                _movieRepository.Update(movie);
            }

            _rentalRepository.Commit();
            _movieRepository.Commit();

            return(Ok());
        }