Пример #1
0
        public IPagedList <BookISBNGroupModel> GetBookListByISBNGroup(SearchBookModel search, int pageIndex, int pageSize)
        {
            using (var dbContext = new MissionskyOAEntities())
            {
                var query      = DoSearch(dbContext, search); //查询
                var groupQuery = query.GroupBy(x => x.ISBN).Select(group =>
                                                                   new
                {
                    ISBN  = group.Key,
                    books = group.Where(it => it.Id != null)
                });

                List <BookISBNGroupModel> bookGroupList = new List <BookISBNGroupModel>();

                groupQuery.ToList().ForEach(item =>
                {
                    BookISBNGroupModel temp = new BookISBNGroupModel()
                    {
                        books = new List <BookModel>()
                    };
                    temp.ISBN = item.ISBN;
                    item.books.ToList().ForEach(i =>
                    {
                        temp.books.Add(DoFill(i.ToModel()));
                    });
                    temp.amount = item.books.ToList().Count;
                    temp.books  = temp.books.OrderByDescending(it => it.Rating.AverageRating).ToList();
                    bookGroupList.Add(temp);
                });
                return(new PagedList <BookISBNGroupModel>(bookGroupList, pageIndex, pageSize));
            }
        }
Пример #2
0
        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                ApplicationUser user = db.Users.Find(User.Identity.GetUserId());
                // создаем список книг, принадлежащих текущему пользователю
                ViewBag.UserBooks = db.Books.ToList().Find(x => x.Owner == user);
                // создаем список новых заявок, поступивших пользователю
                var suggestions = _bidHelper.CreateListOfNewBidsToUser(user);
                if (suggestions.Count > 0)
                {
                    Session["Suggestions"] = suggestions.Count;
                }
                // создаем список обработанных заявок для отображения в истории заявок
                var bids  = _bidHelper.CreateBidList(user);
                int count = _bidHelper.GetNewBidsCount(bids, user);
                if (count > 0)
                {
                    Session["Bids"] = count;
                }
            }

            SearchBookModel model = new SearchBookModel();

            model.CreateLists();
            ViewBag.Genres = db.Genres.ToList();

            return(View(model));
        }
Пример #3
0
        public SearchBookModel BookForIssued([FromUri] SearchBookModel searchBook)
        {
            var BookList = db.Books.Select(x => new SearchBookModel
            {
                AuthorName      = x.Author.AuthorName,
                ID              = x.ID,
                BookName        = x.BookName,
                EditionNo       = x.EditionNo,
                PublicationName = x.Publication.PublicationName,
                PublicationDate = x.PublicationDate,
                AvailAbleBook   = x.BookCopy - x.LoanCopy,
                ISBN            = x.ISBN,
                CoverPhoto      = x.CoverPhoto
            }).AsQueryable();
            SearchBookModel books = new SearchBookModel();

            if (!string.IsNullOrEmpty(searchBook.BookName))
            {
                books = BookList.Where(x => x.BookName == searchBook.BookName).SingleOrDefault();
            }

            if (!string.IsNullOrEmpty(searchBook.ISBN))
            {
                books = BookList.Where(x => x.ISBN == searchBook.ISBN).SingleOrDefault();
            }



            return(books);
        }
        public async Task <IEnumerable <BookViewModel> > Get([FromQuery] SearchBookModel model)
        {
            var result = await queryDispatcher.DispatchAsync <FindBooksQuery, FindBooksQueryResult>(new FindBooksQuery
                                                                                                    { Filter = model.Filter, SortOption = model.SortOption });

            return(result.Books);
        }
Пример #5
0
        public List <SearchBookModel> BookBySpecificSearch([FromUri] SearchBookModel searchBook)
        {
            var BookList = db.Books.Select(x => new SearchBookModel
            {
                AuthorName      = x.Author.AuthorName,
                ID              = x.ID,
                BookName        = x.BookName,
                EditionNo       = x.EditionNo,
                PublicationName = x.Publication.PublicationName,
                PublicationDate = x.PublicationDate,
                AvailAbleBook   = x.BookCopy - x.LoanCopy,
                CoverPhoto      = x.CoverPhoto
            }).AsQueryable();

            List <SearchBookModel> books = new List <SearchBookModel>();

            if (!string.IsNullOrEmpty(searchBook.BookName))
            {
                books = BookList.Where(x => x.BookName.StartsWith(searchBook.BookName)).ToList();
            }

            if (!string.IsNullOrEmpty(searchBook.AuthorName))
            {
                books = BookList.Where(x => x.AuthorName.StartsWith(searchBook.AuthorName)).ToList();
            }
            if (!string.IsNullOrEmpty(searchBook.PublicationName))
            {
                books = BookList.Where(x => x.PublicationName.StartsWith(searchBook.PublicationName)).ToList();
            }



            return(books);
        }
Пример #6
0
        public ApiPagingListResponse <BookModel> SearchBooks(SearchBookModel search, int pageIndex = 0, int pageSize = 25)
        {
            //查询满足条件的图书
            var query = this.BookService.SearchBooks(search, pageIndex, pageSize);

            //查询结果
            var result = new PaginationModel <BookModel>();

            result.Result = query.Result;

            //分页
            result.Page = new Page()
            {
                PageIndex  = query.PageIndex,
                PageSize   = query.PageSize,
                TotalPages = query.TotalPages,
                TotalCount = query.TotalCount
            };

            return(new ApiPagingListResponse <BookModel>
            {
                Result = query.Result,
                Page = result.Page
            });
        }
Пример #7
0
        public ApiListResponse <BookModel> GetBookList(SearchBookModel search)
        {
            var books = this.BookService.GetBookList(search);

            var response = new ApiListResponse <BookModel>()
            {
                Result = books.ToList()
            };

            return(response);
        }
Пример #8
0
        /// <summary>
        /// 查询满足条件的图书
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <returns>满足条件的图书列表</returns>
        public IList <BookModel> GetBookList(SearchBookModel search)
        {
            using (var dbContext = new MissionskyOAEntities())
            {
                var query = DoSearch(dbContext, search); //查询
                var list  = new List <BookModel>();

                query.ToList().ForEach(entity => list.Add(DoFill(entity.ToModel())));
                list = list.OrderByDescending(it => it.Rating.AverageRating).ToList();

                return(list);
            }
        }
Пример #9
0
        /// <summary>
        /// 分页查询图书
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns>满足条件的图书</returns>
        public IPagedList <BookModel> SearchBooks(SearchBookModel search, int pageIndex, int pageSize)
        {
            using (var dbContext = new MissionskyOAEntities())
            {
                var query  = DoSearch(dbContext, search); //查询
                var result = new List <BookModel>();

                query.ToList().ForEach(entity => result.Add(DoFill(entity.ToModel())));
                result = result.OrderByDescending(it => it.Rating.AverageRating).ToList();

                return(new PagedList <BookModel>(result, pageIndex, pageSize));
            }
        }
Пример #10
0
        public ActionResult Search()
        {
            if (User.Identity.IsAuthenticated)
            {
                ApplicationUser user = db.Users.Find(User.Identity.GetUserId());
                ViewBag.UserBooks = db.Books.ToList().Find(x => x.Owner == user);
            }
            SearchBookModel model = new SearchBookModel();

            model.CreateLists();
            ViewBag.Genres = db.Genres.ToList();

            return(View("Index", model));
        }
Пример #11
0
        public ActionResult Search(SearchBookModel model, int[] selectedGenres)
        {
            if (ModelState.IsValid)
            {
                double priceLow  = 0;
                double priceHigh = 0;
                // проверяем диапазон цен
                if (model.PriceLow != null && model.PriceHigh != null)
                {
                    priceLow  = Convert.ToDouble(model.PriceLow);
                    priceHigh = Convert.ToDouble(model.PriceHigh);
                }
                // если одно из полей диапазона заполнено, а другое нет
                if ((model.PriceLow != null && model.PriceHigh == null) ||
                    (model.PriceLow == null && model.PriceHigh != null))
                {
                    ModelState.AddModelError("", "Одно из полей не заполнено (цена)");
                }
                // проверяем диапазон годов издания
                else if (model.PublishYearFrom > model.PublishYearTo)
                {
                    ModelState.AddModelError("", "Левая граница интервала больше правой (год издания)");
                }
                else if (priceLow < 0 || priceHigh < 0)
                {
                    ModelState.AddModelError("", "Некорректная цена");
                }
                else if (priceLow > priceHigh)
                {
                    ModelState.AddModelError("", "Левая граница интервала больше правой (цена)");
                }
                // если все данные корректны, выполняем поиск
                else
                {
                    List <Book> books = new List <Book>();

                    books = _searchHelper.Search(model, selectedGenres);
                    return(View(books));
                }
            }

            ViewBag.Genres = db.Genres.ToList();
            model.CreateLists();

            return(View("Index", model));
        }
Пример #12
0
        public void SelectBook(SearchBookModel bookModel)
        {
            var saveOrderedBookModel = OrderedBooks.FirstOrDefault(ob => ob.BookId == bookModel.Id);

            if (saveOrderedBookModel == null)
            {
                saveOrderedBookModel = new SaveOrderedBookModel
                {
                    BookId    = bookModel.Id,
                    BookTitle = bookModel.BookTitle,
                    Amount    = 0,
                    Price     = bookModel.Price,
                    MaxAmount = bookModel.Amount
                };
                OrderedBooks.Add(saveOrderedBookModel);
            }
            saveOrderedBookModel.Amount += 1;
        }
Пример #13
0
        /// <summary>
        /// 图书查询
        /// </summary>
        /// <param name="dbContext">数据库上下文对象</param>
        /// <param name="search">查询条件</param>
        /// <returns>满足条件的图收列表</returns>
        private IEnumerable <Book> DoSearch(MissionskyOAEntities dbContext, SearchBookModel search)
        {
            var query = dbContext.Books.AsEnumerable();

            //状态查询
            if (search != null && search.Status != BookStatus.None)
            {
                query =
                    query.Where(
                        it =>
                        (!it.Status.HasValue && search.Status == BookStatus.Stored) ||
                        (it.Status.HasValue && search.Status == (BookStatus)it.Status));
            }

            //项目查询
            if (search != null && !string.IsNullOrEmpty(search.Name))
            {
                query = query.Where(it => !string.IsNullOrEmpty(it.Name) && it.Name.Contains(search.Name));
            }

            //二维码
            if (search != null && !string.IsNullOrEmpty(search.BarCode))
            {
                query = query.Where(it => !string.IsNullOrEmpty(it.BarCode) && it.BarCode.Equals(search.BarCode, StringComparison.InvariantCultureIgnoreCase));
            }

            //二维码
            if (search != null && !string.IsNullOrEmpty(search.ISBN))
            {
                query = query.Where(it => !string.IsNullOrEmpty(it.ISBN) && it.ISBN.Equals(search.ISBN, StringComparison.InvariantCultureIgnoreCase));
            }
            //状态
            if (search != null && search.Source != BookSource.None)
            {
                query =
                    query.Where(
                        it =>
                        (!it.Source.HasValue && search.Source == BookSource.Purchase) ||
                        (it.Source.HasValue && it.Source == (int)search.Source));
            }
            return(query);
        }
Пример #14
0
        /// <summary>
        /// Возвращает список найденных книг по запросу пользователя
        /// </summary>
        /// <param name="model"></param>
        /// <param name="selectedGenres"></param>
        /// <returns></returns>
        public List <Book> Search(SearchBookModel model, int[] selectedGenres)
        {
            List <Book> books = new List <Book>();
            // формируем строковый запрос к БД
            string query = "SELECT * FROM dbo.Books WHERE ";

            // поиск по автору
            query += model.Author != null ? "Author LIKE N'%" + model.Author + "%' and " : "";
            // поиск по названию
            query += model.Title != null ? "Title LIKE N'%" + model.Title + "%' and " : "";
            // поиск по цене
            query += (model.PriceLow != null && model.PriceHigh != null) ? "Price between " + model.PriceLow.Replace(',', '.') + " and " + model.PriceHigh.Replace(',', '.') + " and " : "";
            // поиск в интервале по году издания
            query += model.PublishYearFrom != DateTime.Now.Year ? "PublishYear between " + model.PublishYearFrom + " and " + model.PublishYearTo + " and " : "";
            // поиск по нас. пункту владельца
            query += model.Placement != null ? "Placement LIKE N'%" + model.Placement + "%' and " : "";
            int i = model.OnExchange ? 1 : 0;

            // поиск по обмену
            query += "OnExchange = " + i + " and ";
            // поиск по жанрам
            if (selectedGenres != null)
            {
                query += "Books.ID in ( SELECT Book_ID FROM dbo.GenreBooks WHERE Genre_ID IN (SELECT Genres.ID FROM dbo.Genres WHERE Genres.ID in (";
                foreach (var genre in db.Genres.Where(x => selectedGenres.Contains(x.ID)))
                {
                    query += genre.ID + ",";
                }
                query  = query.Remove(query.LastIndexOf(','));
                query += "))) and ";
            }
            if (query.LastIndexOf(" and ") != -1)
            {
                query = query.Remove(query.LastIndexOf(" and "));
                books = db.Books.SqlQuery(query).ToList();
            }
            // сортируем список книг вначале по дате создания профиля по убыванию, затем - по имени владельца
            var sortedBooks = books.OrderByDescending(x => x.Created).ThenBy(x => x.Owner.Name);

            return(sortedBooks.ToList());
        }
Пример #15
0
        private void SelectBook(SearchBookModel book)
        {
            //var bookModel = new SaveOrderedBookModel
            //{
            //    Amount = book.Amount,
            //    Price = book.Price,
            //    BookId = book.BookId,
            //    BookTitle = book.BookTitle
            //};

            SaveOrderedBookModel bookModel = OrderedBooks.FirstOrDefault(ob => ob.BookId == book.BookId);

            if (bookModel == null)
            {
                bookModel           = new SaveOrderedBookModel().CopyProperties(book);
                bookModel.Amount    = 0;
                bookModel.MaxAmount = book.Amount;
                OrderedBooks.Add(bookModel);
            }

            bookModel.Amount += 1;
        }