public async Task CreateBook(RequestCreateBookViewModel request) { Book book = _mapper.Map <Book>(request); await _bookRepository.Create(book); List <Author> authors = await _authorRepository.GetAuthorsByNames(request.Authors); IEnumerable <string> authorsNames = authors.Select(author => author.Name); IEnumerable <string> uncreatedAuthors = request.Authors.Except(authorsNames); var authorsToCreate = new List <Author>(); foreach (string item in uncreatedAuthors) { var authorToCreate = new Author(); authorToCreate.Name = item; authorsToCreate.Add(authorToCreate); } if (authorsToCreate.Count != default(int)) { await _authorRepository.CreateRange(authorsToCreate); authors.AddRange(authorsToCreate); } var authorsBooksToCreate = new List <AuthorBooks>(); foreach (Author author in authors) { var authorBookToCreate = new AuthorBooks(); authorBookToCreate.AuthorId = author.Id; authorBookToCreate.BookId = book.Id; authorsBooksToCreate.Add(authorBookToCreate); } if (authorsBooksToCreate.Count != default(int)) { await _authorBooksRepository.CreateRange(authorsBooksToCreate); } }
public async Task <IActionResult> CreateBook([FromBody] RequestCreateBookViewModel requestModel) { await _bookService.CreateBook(requestModel); return(Ok()); }