public async Task <AuthorDto> Merge(AuthorMergeDto authorMergeDto) { await using var transaction = _context.Database.BeginTransaction(); authorMergeDto.Author.IsConfirmed = true; authorMergeDto.Author.Id = null; var author = _mapper.Map <Author>(authorMergeDto.Author); var bookIds = await _bookAuthorRepository.GetAll().Where(x => authorMergeDto.Authors.Contains(x.AuthorId)).Select(x => x.BookId).Distinct().ToListAsync(); var authors = await _authorRepository.GetAll().Where(x => authorMergeDto.Authors.Contains(x.Id)).ToListAsync(); _authorRepository.RemoveRange(authors); await _authorRepository.SaveChangesAsync(); var newBookAuthors = new List <BookAuthor>(); foreach (var id in bookIds) { newBookAuthors.Add(new BookAuthor() { AuthorId = author.Id, BookId = id }); } author.BookAuthor = newBookAuthors; _authorRepository.Add(author); var affectedRows = await _authorRepository.SaveChangesAsync(); transaction.Commit(); return(affectedRows > 0 ? _mapper.Map <AuthorDto>(author) : null); }
public async Task <IActionResult> PutAuthor([FromBody] AuthorMergeDto authorDto) { var author = await _authorService.Merge(authorDto); if (author == null) { return(BadRequest()); } return(CreatedAtAction("GetAuthor", new { id = author.Id }, author)); }