コード例 #1
0
        public async Task <ActionResult <OptionDto> > UpdateOption(Guid questionId, Guid optionId, [FromBody] UpdateOptionDto option)
        {
            if (option == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!await _questionRepository.isExists(questionId))
            {
                return(NotFound());
            }

            var optionFromRepo = await _optionRepository.GetOptionAsync(questionId, optionId);

            if (optionFromRepo == null)
            {
                var optionToAdd = _mapper.Map <Option>(option);
                optionToAdd.Id = optionId;
                _questionRepository.AddOptionForQuestion(questionId, optionToAdd);

                if (!await _optionRepository.SaveChangesAsync())
                {
                    throw new Exception($"Upserting option {optionId} for question {questionId} failed on save.");
                }

                var optionToReturn = _mapper.Map <OptionDto>(optionToAdd);
                return(CreatedAtRoute("GetOption", new { id = optionToReturn.Id }, optionToReturn));
            }

            _mapper.Map(option, optionFromRepo);
            _optionRepository.Update(optionFromRepo);

            if (!await _optionRepository.SaveChangesAsync())
            {
                throw new Exception($"Upserting option {optionId} for question {questionId} failed on update.");
            }

            return(NoContent());
        }