public async Task <IActionResult> Post([FromBody] NovelPostDto value) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var newNovel = await _novelsService.AddNovel(value); return(CreatedAtRoute("GetNovel", new { id = newNovel.Id }, newNovel)); } catch (DeepValidationException e) { _logger.LogMethodError(e); ModelState.AddModelError(e.Key, e.Error); return(BadRequest(ModelState)); } catch (Exception e) { _logger.LogMethodError(e); return(BadRequest()); } }
public async Task <NovelDto> AddNovel(NovelPostDto novelDto) { var newnovel = new Novel { Title = novelDto.Title, AltTitlesCollection = novelDto.AltTitles.ToImmutableArray() }; // set type var type = await _dbContext.Types.FindAsync(novelDto.TypeId); newnovel.Type = type ?? throw new DeepValidationException(nameof(novelDto.TypeId), $"Type with id:{novelDto.TypeId} was not found"); newnovel.Genres = new List <NovelGenre>(); foreach (var genreId in novelDto.GenreIds) { var genre = await _dbContext.Genres.FindAsync(genreId); if (genre == null) { throw new DeepValidationException(nameof(novelDto.GenreIds), $"Genre with id:{genreId} was not found"); } newnovel.Genres.Add(new NovelGenre { Genre = genre }); } newnovel.Tags = new List <NovelTag>(); foreach (var tagId in novelDto.TagIds) { var tag = await _dbContext.Tags.FindAsync(tagId); if (tag == null) { throw new DeepValidationException(nameof(novelDto.TagIds), $"Tag with id:{tagId} was not found"); } newnovel.Tags.Add(new NovelTag { Tag = tag }); } await _dbContext.Novels.AddAsync(newnovel); await _dbContext.SaveChangesAsync(); return(_mapper.Map <NovelDto>(newnovel)); }