public IHttpActionResult Choose() { var books = _booksService.GetAll() .Distinct(new BooksEqualityComparer()) .ToList(); var authorIds = books.Select(b => b.AuthorId).ToList(); var authors = _authorService.Get(authorIds); var bookDtoList = books .Select(x => new BookDto { Author = CreateAuthorDto(authors, x.AuthorId), Id = x.Id, Title = x.Title }) .ToList(); var response = new BooksDto { Books = bookDtoList }; return(Ok(response)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); using (var dbContext = app.ApplicationServices.GetService <BookContext>()) { var books = new BooksDto[] { new BooksDto { Id = 1, Title = "book1" }, new BooksDto { Id = 2, Title = "book2" } }; foreach (var book in books) { dbContext.Books.Add(book); } dbContext.SaveChanges(); } }
public async Task <IHttpActionResult> SearchBook([FromUri] SearchParam param) { if (!ModelState.IsValid) { DtoBase NG_result = new DtoBase(); NG_result.Status = ApiStatusCode.StatusIllegalArg.GetStatusCode(); NG_result.Message = ApiStatusCode.StatusIllegalArg.GetMessage(); NG_result.Data = null; return(Ok(NG_result)); } // bookとauthorを結合し引数のtitleを含むbookを検索 var qbooks = from x in db.Books join y in db.Authors on x.AuthorId equals y.AuthorId select new BookInfo() { Author = y.Name, Genre = x.Genre, Title = x.Title }; List <BookInfo> books = null; if (param != null) { if (!String.IsNullOrEmpty(param.title)) { qbooks = qbooks.Where(s => s.Title.Contains(param.title)); } } else { books = await qbooks.ToListAsync(); } var OK_result = new BooksDto(); if (books == null || books.Count == 0) { // 結果にステータスコードとメッセージを設定(NotFound) OK_result.Status = ApiStatusCode.StatusNotFound.GetStatusCode(); OK_result.Message = ApiStatusCode.StatusNotFound.GetMessage() + string.Join(",", Request.GetQueryNameValuePairs().Select(e => e.Key + ":" + e.Value).ToArray()); } else { // 結果にステータスコードとメッセージを設定(OK) OK_result.Status = ApiStatusCode.StatusOK.GetStatusCode(); OK_result.Message = ApiStatusCode.StatusOK.GetMessage(); // 取得データを格納 OK_result.Data = books; } return(Ok(OK_result)); }
public IActionResult CreateBook(int authorId, [FromBody] BooksForCreationDto book) { //Validations if (book == null) { return(BadRequest()); } if (book.Name == book.Description) { ModelState.AddModelError("Description", "The book name and the description cannot be the same"); } //Is the model in a valid state if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var author = AuthorsDatastore.Current.Authors.FirstOrDefault(c => c.Id == authorId); if (author == null) { return(NotFound("Author was not found")); } //Demo Purpose will be improved //Get Max Book Id var maxBookId = AuthorsDatastore.Current.Authors.SelectMany(a => a.Books).Max(b => b.Id); //The above method is slow //The above method does not take into account scenarios where multiple users will try to get an ID simultaneously var newBook = new BooksDto() { Id = ++maxBookId, Name = book.Name, Description = book.Description }; author.Books.Add(newBook); //return Ok(author.Books); //For Post the advised response is 201 Created return(CreatedAtRoute("GetbookByAuthorId", new { authorId = authorId, bookid = newBook.Id }, newBook)); }
public BooksResponseModel GetAllBooks() { BooksResponseModel booksResponseModel = new BooksResponseModel(); booksResponseModel.Data = new List <BooksDto>(); DataTable dataTable = new DataTable(); SqlConnection conn = new SqlConnection(DbHelper.DbConnectionString); try { SqlCommand command = new SqlCommand(@"dbo.uspGetAllBooks", conn); command.CommandType = CommandType.StoredProcedure; conn.Open(); SqlDataAdapter dataAdapter = new SqlDataAdapter(command); dataAdapter.Fill(dataTable); booksResponseModel.Message = "Success"; booksResponseModel.StatusCode = 200; foreach (DataRow row in dataTable.Rows) { BooksDto booksModel = new BooksDto(); booksModel.BookID = row["BookID"] != DBNull.Value ? Convert.ToInt64(row["BookID"].ToString()) : 0; booksModel.MainTopicID = row["MainTopicID"] != DBNull.Value ? Convert.ToInt64(row["MainTopicID"].ToString()) : 0; booksModel.MainTopicNumber = row["MainTopicNumber"] != DBNull.Value ? Convert.ToString(row["MainTopicNumber"]) : string.Empty; booksModel.BookDescription = row["BookDescription"] != DBNull.Value ? Convert.ToString(row["BookDescription"].ToString()) : string.Empty; booksResponseModel.Data.Add(booksModel); } } catch (Exception ex) { booksResponseModel.StatusCode = 500; booksResponseModel.Message = ex.Message; booksResponseModel.Data = null; } finally { dataTable.Clear(); dataTable = null; conn.Close(); } return(booksResponseModel); }
public IHttpActionResult DeleteBook(int id) { Book book = db.Books.Find(id); if (book == null) { return(NotFound()); } var response = new BooksDto() { Id = book.Id, Title = book.Title, CoverUrl = book.CoverURL }; db.Books.Remove(book); db.SaveChanges(); return(Ok(response)); }
public async Task <ActionResult <BooksDto> > GetBooks(int id) { Books book = await _context.Books.FindAsync(id); Authors author = await _context.Authors.FindAsync(book.AuthorId); if (book == null) { return(NotFound()); } BooksDto bookDto = new BooksDto { BookId = book.BookId, Title = book.Title, Pages = book.Pages, Price = book.Price, AuthorName = author.Name }; return(bookDto); }
private BooksDto CreateLinksForBooks(BooksDto book) { book.Links.Add(new LinkDto(_urlHelper.Link("GetBookForAuthor", new { Id = book.Id }), "self", "GET")); book.Links.Add(new LinkDto(_urlHelper.Link("DeleteBookForAuthor", new { Id = book.Id }), "delete_book", "DELETE")); book.Links.Add(new LinkDto(_urlHelper.Link("UpdateBookForAuthor", new { Id = book.Id }), "update_book", "PUT")); book.Links.Add(new LinkDto(_urlHelper.Link("PartiallyUpdateBookForAuthor", new { Id = book.Id }), "partially_update_book", "PATCH")); return(book); }