public async Task <ActionResult <GetAuthorDetailsResponse> > AddAnAuthor([FromBody] PostAuthorRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } else { var author = new Author { FirstName = request.FirstName, LastName = request.LastName }; try { _context.Authors.Add(author); await _context.SaveChangesAsync(); var response = new GetAuthorDetailsResponse(author.Id, author.FirstName, author.LastName); return(CreatedAtRoute("get-author-by-id", new { Id = author.Id }, response)); } catch (DbUpdateException) // That author already exists! { // options here: You could return OK or Accepted. I mean, you did what the person wanted. // Or you could return a 303 - see other. we'll do that because it is more fun. var id = await _context.Authors.Where(a => a.FirstName == request.FirstName && a.LastName == request.LastName) .Select(a => a.Id).SingleOrDefaultAsync(); Response.Headers.Add("Location", Url.RouteUrl("get-author-by-id", new { Id = id })); return(StatusCode(303)); } } }
public async Task <GetBooksResponse> GetAsync() { var data = await _dbContext.Books .Include(b => b.Author).ToListAsync(); var embeddedBooks = new List <GetBookDetailsResponse>(); foreach (var book in data) { var authorLinks = new List <Link>(); authorLinks.Add(_authorLinks.GetAuthorDetailsLink(book.Author.Id)); authorLinks.AddRange(_authorLinks.GetLinks()); var author = new GetAuthorDetailsResponse(book.Author.FirstName, book.Author.LastName) { Links = authorLinks }; embeddedBooks.Add(new GetBookDetailsResponse(book.ISBN, book.Title) { Embedded = new List <GetAuthorDetailsResponse>() { author }, Links = _bookLinks.GetBookDetailsLinks(book.ISBN, book.Author.Id).ToList() }); } return(new GetBooksResponse() { Embedded = embeddedBooks, Links = _bookLinks.GetBooksLinks().ToList() }); }
public async Task <ActionResult> UpdateAuthor(int id, [FromBody] GetAuthorDetailsResponse request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } else { var savedAuthor = await _context.Authors.SingleOrDefaultAsync(a => a.Id == id); if (savedAuthor == null) { return(NotFound()); } else { savedAuthor.FirstName = request.FirstName; savedAuthor.LastName = request.LastName; await _context.SaveChangesAsync(); return(NoContent()); } } }