Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Execute paged queries on the driver instead of blocking a thread (#771)
Krzysztof Pajak52a5df439d14
diff --git a/.ai/knowledge/async.md b/.ai/knowledge/async.mdindex 7c69a6808..dc03fdcf7 100644--- a/.ai/knowledge/async.md+++ b/.ai/knowledge/async.md@@ -63,16 +63,35 @@ var result = await _repository.GetByIdAsync(id);`ValueTask` avoids allocation for code that often returns a cached result without awaiting. Do not retrofit existing `Task`-returning code unless profiling shows allocation is a problem.-### Avoid `.ToList()` inside async lambdas passed to cache+### Never execute a query built on `Table` synchronously-`IQueryable<T>.ToList()` is synchronous and blocks. Use LINQ's `ToList()` only on in-memory sequences, or use repository methods that return `Task<IList<T>>`.+`Table` is an `IQueryable` over the MongoDB driver. `ToList()`, `Count()`, `First()` and plain+enumeration on it each issue a **blocking** round trip and hold a thread pool thread for its+duration. Being MongoDB rather than EF does not make it synchronous-safe — it makes it a network+call with no async on that path unless you ask for one.++Execute through the repository instead. `MongoRepository` runs the query on the driver's+asynchronous API. Hand it a sequence you already materialised and it throws — that is deliberate,+because quietly enumerating it would be the very pattern this rule exists to remove.```csharp-// This is fine — the LINQ query is materialised synchronously here-// because Table is IQueryable against MongoDB, not EF+// wrong — blocks a thread for the whole round tripvar productIds = query.Take(request.ProductsNumber).ToList();+var total = query.Count();+return new PagedList<Product>(query, pageIndex, pageSize);++// correct+var productIds = await _productRepository.ToListAsync(query.Take(request.ProductsNumber));+var total = await _productRepository.CountAsync(query);+return await _productRepository.PagedAsync(query, pageIndex, pageSize);```+The same applies inside a lambda passed to `ICacheBase.GetAsync` — make the lambda `async` and+await the repository, rather than returning `Task.FromResult(query.ToList())`. Blocking there is+worse than elsewhere, because the cache holds a lock while the acquire function runs.++`ToList()` on a sequence that is already in memory is fine and needs no repository call.+### Run independent operations concurrently with `Task.WhenAll`When two or more async operations are independent, start all of them before awaiting:diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.csindex d4c230245..d35ee0973 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.cs@@ -33,6 +33,6 @@ public classquery = query.Where(duh => duh.Canceled == request.Canceled.Value);query = query.OrderByDescending(c => c.CreatedOnUtc);- return await PagedList<DiscountUsageHistory>.Create(query, request.PageIndex, request.PageSize);+ return await _discountUsageHistoryRepository.PagedAsync(query, request.PageIndex, request.PageSize);}}\ No newline at end of filediff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.csindex 7326acf50..d7aaeac93 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs@@ -51,7 +51,7 @@ public class GetSearchProductsQueryHandler : IRequestHandler<GetSearchProductsQuquery = OrderByQueryable(request, query);// Create paged list- var products = await PagedList<Product>.Create(query, request.PageIndex, request.PageSize);+ var products = await _productRepository.PagedAsync(query, request.PageIndex, request.PageSize);// Get filterable specification attributes if neededif (ShouldLoadFilterableSpecifications(request))diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.csindex 7e12b8a4d..5b98c661d 100644--- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs@@ -91,7 +91,7 @@ public class BrandService : IBrandService}query = query.OrderBy(m => m.DisplayOrder).ThenBy(m => m.Name);- return await PagedList<Brand>.Create(query, pageIndex, pageSize);+ return await _brandRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.csindex 92dcb5cc8..880e315b3 100644--- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs@@ -111,7 +111,7 @@ public class CategoryService : ICategoryServicequery = query.OrderBy(c => c.DisplayOrder).ThenBy(c => c.Name);//pagination- return await Task.FromResult(new PagedList<Category>(query, pageIndex, pageSize));+ return await _categoryRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.csindex 5411f405c..e29adae7e 100644--- a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs@@ -51,7 +51,7 @@ public class ProductCategoryService : IProductCategoryServicevar key = string.Format(CacheKey.PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY, showHidden, categoryId, pageIndex,pageSize, string.Join(",", _contextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),_contextAccessor.StoreContext.CurrentStore.Id);- return await _cacheBase.GetAsync(key, () =>+ return await _cacheBase.GetAsync(key, async () =>{var query = _productRepository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == categoryId));@@ -91,7 +91,7 @@ public class ProductCategoryService : IProductCategoryServiceorderby pm.DisplayOrderselect pm;- return Task.FromResult(new PagedList<ProductsCategory>(queryProductCategories, pageIndex, pageSize));+ return await _productRepository.PagedAsync(queryProductCategories, pageIndex, pageSize);});}diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.csindex 0175e0f78..2019df160 100644--- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs@@ -95,7 +95,7 @@ public class CollectionService : ICollectionService}query = query.OrderBy(m => m.DisplayOrder).ThenBy(m => m.Name);- return await PagedList<Collection>.Create(query, pageIndex, pageSize);+ return await _collectionRepository.PagedAsync(query, pageIndex, pageSize);}diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.csindex 528fe3310..3f88c0651 100644--- a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs@@ -46,7 +46,7 @@ public class ProductCollectionService : IProductCollectionService{var key = string.Format(CacheKey.PRODUCTCOLLECTIONS_ALLBYCOLLECTIONID_KEY, showHidden, collectionId, pageIndex,pageSize, string.Join(",", _contextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()), storeId);- return await _cacheBase.GetAsync(key, () =>+ return await _cacheBase.GetAsync(key, async () =>{var query = _productRepository.Table.Where(x =>x.ProductCollections.Any(y => y.CollectionId == collectionId));@@ -84,7 +84,7 @@ public class ProductCollectionService : IProductCollectionServiceorderby pm.DisplayOrderselect pm;- return Task.FromResult(new PagedList<ProductsCollection>(queryProductCollection, pageIndex, pageSize));+ return await _productRepository.PagedAsync(queryProductCollection, pageIndex, pageSize);});}diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.csindex 7f79b3a21..2fa55f7ca 100644--- a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs@@ -94,7 +94,7 @@ public class SearchTermService : ISearchTermServiceKeyword = r.Keyword,Count = r.Count});- return await PagedList<SearchTermReportLine>.Create(query, pageIndex, pageSize);+ return await _searchTermRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.csindex c33785698..3fc47a86f 100644--- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs@@ -203,7 +203,7 @@ public class DiscountService : IDiscountServicequery = query.Where(duh => duh.DiscountId == discountId);query = query.OrderByDescending(c => c.CouponCode);- return await PagedList<DiscountCoupon>.Create(query, pageIndex, pageSize);+ return await _discountCouponRepository.PagedAsync(query, pageIndex, pageSize);}diff --git a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.csindex 5ddd03063..ad81bacfa 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs@@ -53,14 +53,14 @@ public class AuctionService : IAuctionServiceint pageSize = int.MaxValue){var query = _bidRepository.Table.Where(x => x.ProductId == productId).OrderByDescending(x => x.Date);- return await Task.FromResult(new PagedList<Bid>(query, pageIndex, pageSize));+ return await _bidRepository.PagedAsync(query, pageIndex, pageSize);}public virtual async Task<IPagedList<Bid>> GetBidsByCustomerId(string customerId, int pageIndex = 0,int pageSize = int.MaxValue){var query = _bidRepository.Table.Where(x => x.CustomerId == customerId);- return await Task.FromResult(new PagedList<Bid>(query, pageIndex, pageSize));+ return await _bidRepository.PagedAsync(query, pageIndex, pageSize);}public virtual async Task InsertBid(Bid bid)diff --git a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.csindex 94eaa9bf4..024342526 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs@@ -58,7 +58,7 @@ public class OutOfStockSubscriptionService : IOutOfStockSubscriptionServicequery = query.OrderByDescending(x => x.CreatedOnUtc);- return await PagedList<OutOfStockSubscription>.Create(query, pageIndex, pageSize);+ return await _outOfStockSubscriptionRepository.PagedAsync(query, pageIndex, pageSize);}diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.csindex e35ebfe4e..534552391 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs@@ -61,7 +61,7 @@ public class ProductAttributeService : IProductAttributeServiceint pageSize = int.MaxValue){var key = string.Format(CacheKey.PRODUCTATTRIBUTES_ALL_KEY, storeId, pageIndex, pageSize);- return await _cacheBase.GetAsync(key, () =>+ return await _cacheBase.GetAsync(key, async () =>{var query = from pa in _productAttributeRepository.Tableselect pa;@@ -74,7 +74,7 @@ public class ProductAttributeService : IProductAttributeServicequery = query.OrderBy(pa => pa.Name);- return Task.FromResult(new PagedList<ProductAttribute>(query, pageIndex, pageSize));+ return await _productAttributeRepository.PagedAsync(query, pageIndex, pageSize);});diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.csindex c2e3e2d93..9948cfeef 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs@@ -56,7 +56,7 @@ public class ProductReservationService : IProductReservationService}query = query.OrderBy(x => x.Date);- return await PagedList<ProductReservation>.Create(query, pageIndex, pageSize);+ return await _productReservationRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.csindex 432521fa1..90803d956 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs@@ -60,7 +60,7 @@ public class ProductReviewService : IProductReviewServicequery = query.OrderByDescending(c => c.CreatedOnUtc);- return await PagedList<ProductReview>.Create(query, pageIndex, pageSize);+ return await _productReviewRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.csindex a72285354..18e2e17a1 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs@@ -153,7 +153,7 @@ public class ProductService : IProductServicewhere c.AppliedDiscounts.Any(x => x == discountId)select c;- return await PagedList<Product>.Create(query, pageIndex, pageSize);+ return await _productRepository.PagedAsync(query, pageIndex, pageSize);}@@ -577,7 +577,7 @@ public class ProductService : IProductServicequery = query.OrderBy(x => x.Name);- return await PagedList<Product>.Create(query, pageIndex, pageSize);+ return await _productRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.csindex e2b1f8359..cebaed7b8 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs@@ -98,7 +98,7 @@ public class SpecificationAttributeService : ISpecificationAttributeServicequery = query.OrderBy(sa => sa.DisplayOrder).ThenBy(sa => sa.Name);- return await PagedList<SpecificationAttribute>.Create(query, pageIndex, pageSize);+ return await _specificationAttributeRepository.PagedAsync(query, pageIndex, pageSize);}diff --git a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.csindex 74e979316..7951491ce 100644--- a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs+++ b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs@@ -79,7 +79,7 @@ public class GiftVoucherService : IGiftVoucherService};var query = await _mediator.Send(model);- return await PagedList<GiftVoucher>.Create(query, pageIndex, pageSize);+ return await _giftVoucherRepository.PagedAsync(query, pageIndex, pageSize);}public virtual async Task<IList<GiftVoucherUsageHistory>> GetAllGiftVoucherUsageHistory(string orderId = "")diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.csindex 9c424c583..22e95ddcf 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs@@ -111,7 +111,7 @@ public class MerchandiseReturnService : IMerchandiseReturnService};var query = await _mediator.Send(model);- return await PagedList<MerchandiseReturn>.Create(query, pageIndex, pageSize);+ return await _merchandiseReturnRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderReportService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderReportService.csindex 4278f4bc9..a27a190bb 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderReportService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderReportService.cs@@ -560,7 +560,7 @@ public class OrderReportService : IOrderReportService(showHidden || p.Published)select p;- return await PagedList<Product>.Create(qproducts, pageIndex, pageSize);+ return await _productRepository.PagedAsync(qproducts, pageIndex, pageSize);}public class OrderStatsdiff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.csindex 7635f9941..068f65c03 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs@@ -197,7 +197,7 @@ public class OrderService : IOrderServiceSalesEmployeeId = salesEmployeeId};var query = await _mediator.Send(queryModel);- return await PagedList<Order>.Create(query, pageIndex, pageSize);+ return await _orderRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.csindex 3b97018ff..29f150a66 100644--- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs@@ -149,7 +149,7 @@ public class PaymentTransactionService : IPaymentTransactionService};var query = await _mediator.Send(model);- return await PagedList<PaymentTransaction>.Create(query, pageIndex, pageSize);+ return await _repositoryPaymentTransaction.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.csindex 158739e31..0abff6904 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs@@ -64,7 +64,7 @@ public class DeliveryDateService : IDeliveryDateServicequery = query.Where(dd => dd.StoreId == storeId);query = query.OrderBy(dd => dd.DisplayOrder);- return await PagedList<DeliveryDate>.Create(query, pageIndex, pageSize);+ return await _deliveryDateRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.csindex a006b4d31..914ed43b5 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs@@ -64,7 +64,7 @@ public class PickupPointService : IPickupPointServicequery = query.Where(pp => pp.StoreId == storeId);query = query.OrderBy(pp => pp.DisplayOrder);- return await PagedList<PickupPoint>.Create(query, pageIndex, pageSize);+ return await _pickupPointsRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.csindex 6f2f81c64..31d994e22 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs@@ -85,7 +85,7 @@ public class ShipmentService : IShipmentServicequery = query.Where(s => createdToUtc.Value >= s.CreatedOnUtc);query = query.OrderByDescending(x => x.CreatedOnUtc);- var shipments = await PagedList<Shipment>.Create(query, pageIndex, pageSize);+ var shipments = await _shipmentRepository.PagedAsync(query, pageIndex, pageSize);return shipments;}diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.csindex a720c13e9..188a3d150 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs@@ -64,7 +64,7 @@ public class WarehouseService : IWarehouseServicequery = query.Where(wh => wh.StoreId == storeId);query = query.OrderBy(wh => wh.DisplayOrder);- return await PagedList<Warehouse>.Create(query, pageIndex, pageSize);+ return await _warehouseRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Cms/Services/BlogService.cs b/src/Business/Grand.Business.Cms/Services/BlogService.csindex 2562d5844..647f75720 100644--- a/src/Business/Grand.Business.Cms/Services/BlogService.cs+++ b/src/Business/Grand.Business.Cms/Services/BlogService.cs@@ -110,7 +110,7 @@ public class BlogService : IBlogServicequery = query.OrderByDescending(b => b.CreatedOnUtc);- return await PagedList<BlogPost>.Create(query, pageIndex, pageSize);+ return await _blogPostRepository.PagedAsync(query, pageIndex, pageSize);}diff --git a/src/Business/Grand.Business.Cms/Services/NewsService.cs b/src/Business/Grand.Business.Cms/Services/NewsService.csindex 435b10b88..4abd31bd2 100644--- a/src/Business/Grand.Business.Cms/Services/NewsService.cs+++ b/src/Business/Grand.Business.Cms/Services/NewsService.cs@@ -97,7 +97,7 @@ public class NewsService : INewsService}query = query.OrderByDescending(n => n.CreatedOnUtc);- return await PagedList<NewsItem>.Create(query, pageIndex, pageSize);+ return await _newsItemRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs b/src/Business/Grand.Business.Common/Services/Directory/GroupService.csindex b36cdebc1..d95393ca8 100644--- a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs@@ -76,7 +76,7 @@ public class GroupService : IGroupServicequery = query.OrderBy(m => m.DisplayOrder).ThenBy(m => m.Name);- return await PagedList<CustomerGroup>.Create(query, pageIndex, pageSize);+ return await _customerGroupRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs b/src/Business/Grand.Business.Common/Services/Seo/SlugService.csindex 626fd6223..7d0909c37 100644--- a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs+++ b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs@@ -148,7 +148,7 @@ public class SlugService : ISlugServicequery = query.Where(ur => ur.IsActive == active.Value);query = query.OrderBy(ur => ur.Slug);- return await PagedList<EntityUrl>.Create(query, pageIndex, pageSize);+ return await _urlEntityRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.csindex cee91a5d7..3e82f876b 100644--- a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs@@ -113,7 +113,7 @@ public interface IPictureService/// <param name="pageIndex">Current page</param>/// <param name="pageSize">Items on each page</param>/// <returns>Paged list of pictures</returns>- IPagedList<Picture> GetPictures(int pageIndex = 0, int pageSize = int.MaxValue);+ Task<IPagedList<Picture>> GetPictures(int pageIndex = 0, int pageSize = int.MaxValue);/// <summary>/// Inserts a picturediff --git a/src/Business/Grand.Business.Core/Interfaces/System/Reports/ICustomerReportService.cs b/src/Business/Grand.Business.Core/Interfaces/System/Reports/ICustomerReportService.csindex 58bc556a5..7f92afe4f 100644--- a/src/Business/Grand.Business.Core/Interfaces/System/Reports/ICustomerReportService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/System/Reports/ICustomerReportService.cs@@ -24,7 +24,7 @@ public interface ICustomerReportService/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>Report</returns>- IPagedList<BestCustomerReportLine> GetBestCustomersReport(string storeId = "", string vendorId = "",+ Task<IPagedList<BestCustomerReportLine>> GetBestCustomersReport(string storeId = "", string vendorId = "",DateTime? createdFromUtc = null,DateTime? createdToUtc = null, int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null,int orderBy = 0,diff --git a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs b/src/Business/Grand.Business.Customers/Services/AffiliateService.csindex 326b778b4..3ed7cc2c0 100644--- a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs+++ b/src/Business/Grand.Business.Customers/Services/AffiliateService.cs@@ -108,7 +108,7 @@ public class AffiliateService : IAffiliateServicequery = query.OrderByDescending(a => a.Id);- return await PagedList<Affiliate>.Create(query, pageIndex, pageSize);+ return await _affiliateRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Customers/Services/CustomerReportService.cs b/src/Business/Grand.Business.Customers/Services/CustomerReportService.csindex 1f0c740e4..fe752a202 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerReportService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerReportService.cs@@ -62,7 +62,7 @@ public class CustomerReportService : ICustomerReportService/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>Report</returns>- public virtual IPagedList<BestCustomerReportLine> GetBestCustomersReport(string storeId = "", string vendorId = "",+ public virtual async Task<IPagedList<BestCustomerReportLine>> GetBestCustomersReport(string storeId = "", string vendorId = "",DateTime? createdFromUtc = null,DateTime? createdToUtc = null, int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null,int orderBy = 0,@@ -101,7 +101,7 @@ public class CustomerReportService : ICustomerReportService_ => throw new ArgumentException("Wrong orderBy parameter", nameof(orderBy))};- var tmp = new PagedList<dynamic>(query2, pageIndex, pageSize);+ var tmp = await _orderRepository.PagedAsync(query2, pageIndex, pageSize);return new PagedList<BestCustomerReportLine>(tmp.Select(x => new BestCustomerReportLine {CustomerId = x.CustomerId,OrderTotal = x.OrderTotal,@@ -135,7 +135,7 @@ public class CustomerReportService : ICustomerReportService_ => throw new ArgumentException("Wrong orderBy parameter", nameof(orderBy))};- var vendorReport = new PagedList<dynamic>(vendorQueryGroup, pageIndex, pageSize);+ var vendorReport = await _orderRepository.PagedAsync(vendorQueryGroup, pageIndex, pageSize);return new PagedList<BestCustomerReportLine>(vendorReport.Select(x => new BestCustomerReportLine {CustomerId = x.CustomerId,OrderTotal = x.OrderTotal,diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.csindex b1a7ea782..7f31bd499 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs@@ -114,7 +114,7 @@ public class CustomerService : ICustomerServiceOrderBySelector = orderBySelector};var query = await _mediator.Send(queryModel);- return await PagedList<Customer>.Create(query, pageIndex, pageSize);+ return await _customerRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>@@ -150,7 +150,7 @@ public class CustomerService : ICustomerServicequery = query.Where(c => c.SeId == salesEmployeeId);query = query.OrderByDescending(c => c.LastActivityDateUtc);- return await PagedList<Customer>.Create(query, pageIndex, pageSize);+ return await _customerRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Customers/Services/UserApiService.cs b/src/Business/Grand.Business.Customers/Services/UserApiService.csindex 73678e965..6e40a2fd0 100644--- a/src/Business/Grand.Business.Customers/Services/UserApiService.cs+++ b/src/Business/Grand.Business.Customers/Services/UserApiService.cs@@ -84,7 +84,7 @@ public class UserApiService : IUserApiServiceif (!string.IsNullOrEmpty(email))query = query.Where(x => x.Email.Contains(email.ToLowerInvariant()));- return await PagedList<UserApi>.Create(query, pageIndex, pageSize);+ return await _userRepository.PagedAsync(query, pageIndex, pageSize);}#region Fieldsdiff --git a/src/Business/Grand.Business.Customers/Services/VendorService.cs b/src/Business/Grand.Business.Customers/Services/VendorService.csindex 616cceb60..4000ace73 100644--- a/src/Business/Grand.Business.Customers/Services/VendorService.cs+++ b/src/Business/Grand.Business.Customers/Services/VendorService.cs@@ -76,7 +76,7 @@ public class VendorService : IVendorServicequery = query.Where(v => v.Active);query = query.Where(v => !v.Deleted);query = query.OrderBy(v => v.DisplayOrder).ThenBy(v => v.Name);- return await PagedList<Vendor>.Create(query, pageIndex, pageSize);+ return await _vendorRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>@@ -218,7 +218,7 @@ public class VendorService : IVendorServiceif (!string.IsNullOrEmpty(vendorId))query = query.Where(c => c.VendorId == vendorId);query = query.OrderByDescending(c => c.CreatedOnUtc);- return await PagedList<VendorReview>.Create(query, pageIndex, pageSize);+ return await _vendorReviewRepository.PagedAsync(query, pageIndex, pageSize);}diff --git a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.csindex e8eeb4ed8..145b945c3 100644--- a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs@@ -111,7 +111,7 @@ public class CampaignService(where c.CampaignId == campaign.Idorderby c.CreatedDateUtc descendingselect c;- return await PagedList<CampaignHistory>.Create(query, pageIndex, pageSize);+ return await campaignHistoryRepository.PagedAsync(query, pageIndex, pageSize);}public virtual async Task<IPagedList<NewsLetterSubscription>> CustomerSubscriptions(Campaign campaign,@@ -119,7 +119,7 @@ public class CampaignService({ArgumentNullException.ThrowIfNull(campaign);- PagedList<NewsLetterSubscription> model;+ IPagedList<NewsLetterSubscription> model;if (campaign.CustomerCreatedDateFrom.HasValue || campaign.CustomerCreatedDateTo.HasValue ||campaign.CustomerHasShoppingCart is not (CampaignCondition.All and CampaignCondition.All) ||campaign.CustomerLastActivityDateFrom.HasValue || campaign.CustomerLastActivityDateTo.HasValue ||@@ -197,7 +197,7 @@ public class CampaignService(if (campaign.NewsletterCategories.Count > 0)foreach (var item in campaign.NewsletterCategories)query = query.Where(x => x.NewsletterCategories.Contains(item));- model = await PagedList<NewsLetterSubscription>.Create(+ model = await newsLetterSubscriptionRepository.PagedAsync(query.Select(x => new NewsLetterSubscription {CustomerId = x.CustomerId, Email = x.Email,NewsLetterSubscriptionGuid = x.NewsLetterSubscriptionGuid@@ -212,7 +212,7 @@ public class CampaignService(if (campaign.NewsletterCategories.Count > 0)foreach (var item in campaign.NewsletterCategories)query = query.Where(x => x.Categories.Contains(item));- model = await PagedList<NewsLetterSubscription>.Create(query, pageIndex, pageSize);+ model = await newsLetterSubscriptionRepository.PagedAsync(query, pageIndex, pageSize);}return await Task.FromResult(model);diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.csindex 301b00e48..dc858f5d1 100644--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs@@ -79,7 +79,7 @@ public class ContactUsService : IContactUsServicequery = query.Where(l => l.Email.ToLower().Contains(email.ToLower()));query = query.OrderByDescending(x => x.CreatedOnUtc);- var contactus = await PagedList<ContactUs>.Create(query, pageIndex, pageSize);+ var contactus = await _contactusRepository.PagedAsync(query, pageIndex, pageSize);return contactus;}diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.csindex bc2c6db22..d7761566b 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs@@ -45,7 +45,7 @@ public class CourseService : ICourseServiceorderby q.DisplayOrderselect q;- return await PagedList<Course>.Create(query, pageIndex, pageSize);+ return await _courseRepository.PagedAsync(query, pageIndex, pageSize);}public virtual async Task<IList<Course>> GetByCustomer(Customer customer, string storeId)diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.csindex a61e431d9..c2cedfdd0 100644--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs@@ -126,7 +126,7 @@ public class CustomerProductService : ICustomerProductServicevar query = from pp in _customerProductPriceRepository.Tablewhere pp.CustomerId == customerIdselect pp;- return await PagedList<CustomerProductPrice>.Create(query, pageIndex, pageSize);+ return await _customerProductPriceRepository.PagedAsync(query, pageIndex, pageSize);}#endregion@@ -219,7 +219,7 @@ public class CustomerProductService : ICustomerProductServicewhere pp.CustomerId == customerIdorderby pp.DisplayOrderselect pp;- return await PagedList<CustomerProduct>.Create(query, pageIndex, pageSize);+ return await _customerProductRepository.PagedAsync(query, pageIndex, pageSize);}#endregiondiff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.csindex 52be576d2..fd223925e 100644--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs@@ -45,7 +45,7 @@ public class CustomerTagService : ICustomerTagServicevar query = from c in _customerRepository.Tablewhere c.CustomerTags.Contains(customerTagId)select c;- return await PagedList<Customer>.Create(query, pageIndex, pageSize);+ return await _customerRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.csindex 2bfae3c4d..41d769a6e 100644--- a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs@@ -61,7 +61,7 @@ public class DocumentService : IDocumentServiceif (status >= 0)query = query.Where(d => d.StatusId == (DocumentStatus)status);- return await PagedList<Document>.Create(query, pageIndex, pageSize);+ return await _documentRepository.PagedAsync(query, pageIndex, pageSize);}diff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.csindex 1b2dc9704..852911480 100644--- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs@@ -238,7 +238,7 @@ public class NewsLetterSubscriptionService : INewsLetterSubscriptionServicequery = query.Where(c => c.Categories.Any(x => categoryIds.Contains(x)));query = query.OrderBy(nls => nls.Email);- return await PagedList<NewsLetterSubscription>.Create(query, pageIndex, pageSize);+ return await _subscriptionRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.csindex 9821c1f57..dce379018 100644--- a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs+++ b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs@@ -116,7 +116,7 @@ public class PushNotificationsService : IPushNotificationsServicepublic virtual async Task<IPagedList<PushMessage>> GetPushMessages(int pageIndex = 0, int pageSize = int.MaxValue){var query = _pushMessagesRepository.Table.OrderByDescending(x => x.SentOn);- return await Task.FromResult(new PagedList<PushMessage>(query, pageIndex, pageSize));+ return await _pushMessagesRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>@@ -126,7 +126,7 @@ public class PushNotificationsService : IPushNotificationsServiceint pageSize = int.MaxValue){var query = _pushRegistrationRepository.Table.OrderByDescending(x => x.RegisteredOn);- return await Task.FromResult(new PagedList<PushRegistration>(query, pageIndex, pageSize));+ return await _pushRegistrationRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs b/src/Business/Grand.Business.Messages/Services/EmailAccountService.csindex 6b1a4a575..4007053ba 100644--- a/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs+++ b/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs@@ -148,6 +148,6 @@ public class EmailAccountService : IEmailAccountServiceif (!string.IsNullOrEmpty(storeId))query = query.Where(ea => ea.StoreId == storeId);- return await PagedList<EmailAccount>.Create(query, pageIndex, pageSize);+ return await _emailAccountRepository.PagedAsync(query, pageIndex, pageSize);}}\ No newline at end of filediff --git a/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs b/src/Business/Grand.Business.Messages/Services/MessageTemplateService.csindex 3467c6e51..150c5f6d3 100644--- a/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs+++ b/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs@@ -161,7 +161,7 @@ public class MessageTemplateService : IMessageTemplateServicequery = query.OrderBy(t => t.Name);- return await PagedList<MessageTemplate>.Create(query, pageIndex, pageSize);+ return await _messageTemplateRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.csindex a49a003c9..99bc1a2e2 100644--- a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs+++ b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs@@ -173,7 +173,7 @@ public class QueuedEmailService : IQueuedEmailService://load by priorityquery.OrderByDescending(qe => qe.PriorityId).ThenBy(qe => qe.CreatedOnUtc);- return await PagedList<QueuedEmail>.Create(query, pageIndex, pageSize);+ return await _queuedEmailRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.csindex 2524e0f05..62d9a073f 100644--- a/src/Business/Grand.Business.Storage/Services/PictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs@@ -528,12 +528,11 @@ public class PictureService : IPictureService/// <param name="pageIndex">Current page</param>/// <param name="pageSize">Items on each page</param>/// <returns>Paged list of pictures</returns>- public virtual IPagedList<Picture> GetPictures(int pageIndex = 0, int pageSize = int.MaxValue)+ public virtual async Task<IPagedList<Picture>> GetPictures(int pageIndex = 0, int pageSize = int.MaxValue){var query = from p in _pictureRepository.Tableselect p;- var pictures = new PagedList<Picture>(query, pageIndex, pageSize);- return pictures;+ return await _pictureRepository.PagedAsync(query, pageIndex, pageSize);}/// <summary>diff --git a/src/Core/Grand.Data/IRepository.cs b/src/Core/Grand.Data/IRepository.csindex d692cf6be..ccf97b0a4 100644--- a/src/Core/Grand.Data/IRepository.cs+++ b/src/Core/Grand.Data/IRepository.cs@@ -158,5 +158,33 @@ public interface IRepository<T> where T : BaseEntity/// <summary>/// Gets a table collection/// </summary>- IQueryable<C> TableCollection<C>() where C : class;+ IQueryable<C> TableCollection<C>() where C : class;++ /// <summary>+ /// Executes the query and returns its results+ /// </summary>+ /// <typeparam name="TResult">Type of the query result - the entity itself or a projection</typeparam>+ /// <param name="query">Query built on top of <see cref="Table" /> or <see cref="TableCollection{C}" /></param>+ /// <param name="cancellationToken">Cancellation token</param>+ Task<IList<TResult>> ToListAsync<TResult>(IQueryable<TResult> query,+ CancellationToken cancellationToken = default);++ /// <summary>+ /// Executes the query and returns the number of matching documents+ /// </summary>+ /// <typeparam name="TResult">Type of the query result - the entity itself or a projection</typeparam>+ /// <param name="query">Query built on top of <see cref="Table" /> or <see cref="TableCollection{C}" /></param>+ /// <param name="cancellationToken">Cancellation token</param>+ Task<int> CountAsync<TResult>(IQueryable<TResult> query, CancellationToken cancellationToken = default);++ /// <summary>+ /// Executes the query and returns a single page of its results+ /// </summary>+ /// <typeparam name="TResult">Type of the query result - the entity itself or a projection</typeparam>+ /// <param name="query">Query built on top of <see cref="Table" /> or <see cref="TableCollection{C}" /></param>+ /// <param name="pageIndex">Zero based page index</param>+ /// <param name="pageSize">Page size</param>+ /// <param name="cancellationToken">Cancellation token</param>+ Task<IPagedList<TResult>> PagedAsync<TResult>(IQueryable<TResult> query, int pageIndex, int pageSize,+ CancellationToken cancellationToken = default);}\ No newline at end of filediff --git a/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs b/src/Core/Grand.Data/LiteDb/LiteDBRepository.csindex 2811e81db..2773a2d16 100644--- a/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs+++ b/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs@@ -419,6 +419,54 @@ public class LiteDBRepository<T> : IRepository<T> where T : BaseEntity#endregion+ #region Query execution++ //LiteDB is an embedded database with no asynchronous API, and Table already materialises the+ //collection before the query runs. These complete synchronously by design - unlike the rest of+ //the codebase, Task.FromResult here is honest rather than a fake async signature.++ /// <summary>+ /// Executes the query and returns its results+ /// </summary>+ public virtual Task<IList<TResult>> ToListAsync<TResult>(IQueryable<TResult> query,+ CancellationToken cancellationToken = default)+ {+ ArgumentNullException.ThrowIfNull(query);++ return Task.FromResult<IList<TResult>>(query.ToList());+ }++ /// <summary>+ /// Executes the query and returns the number of matching documents+ /// </summary>+ public virtual Task<int> CountAsync<TResult>(IQueryable<TResult> query,+ CancellationToken cancellationToken = default)+ {+ ArgumentNullException.ThrowIfNull(query);++ return Task.FromResult(query.Count());+ }++ /// <summary>+ /// Executes the query and returns a single page of its results+ /// </summary>+ public virtual Task<IPagedList<TResult>> PagedAsync<TResult>(IQueryable<TResult> query, int pageIndex,+ int pageSize, CancellationToken cancellationToken = default)+ {+ ArgumentNullException.ThrowIfNull(query);++ //keep the same normalization the paged list applies, so the skip matches the reported page size+ if (pageSize <= 0)+ pageSize = 1;++ var totalCount = query.Count();+ var items = query.Skip(pageIndex * pageSize).Take(pageSize).ToList();++ return Task.FromResult<IPagedList<TResult>>(new PagedList<TResult>(items, pageIndex, pageSize, totalCount));+ }++ #endregion+#region Helpersprivate static string GetName(LambdaExpression lambdaexpression)diff --git a/src/Core/Grand.Data/Mongo/MongoRepository.cs b/src/Core/Grand.Data/Mongo/MongoRepository.csindex 3c0daab9a..69c2116a0 100644--- a/src/Core/Grand.Data/Mongo/MongoRepository.cs+++ b/src/Core/Grand.Data/Mongo/MongoRepository.cs@@ -1,5 +1,6 @@using Grand.Domain;using MongoDB.Driver;+using MongoDB.Driver.Linq;using System.Linq.Expressions;namespace Grand.Data.Mongo;@@ -343,4 +344,48 @@ public class MongoRepository<T> : IRepository<T> where T : BaseEntity}#endregion++ #region Query execution++ /// <summary>+ /// Executes the query and returns its results+ /// </summary>+ public virtual async Task<IList<TResult>> ToListAsync<TResult>(IQueryable<TResult> query,+ CancellationToken cancellationToken = default)+ {+ ArgumentNullException.ThrowIfNull(query);++ return await query.ToListAsync(cancellationToken);+ }++ /// <summary>+ /// Executes the query and returns the number of matching documents+ /// </summary>+ public virtual async Task<int> CountAsync<TResult>(IQueryable<TResult> query,+ CancellationToken cancellationToken = default)+ {+ ArgumentNullException.ThrowIfNull(query);++ return await query.CountAsync(cancellationToken);+ }++ /// <summary>+ /// Executes the query and returns a single page of its results+ /// </summary>+ public virtual async Task<IPagedList<TResult>> PagedAsync<TResult>(IQueryable<TResult> query, int pageIndex,+ int pageSize, CancellationToken cancellationToken = default)+ {+ ArgumentNullException.ThrowIfNull(query);++ //keep the same normalization the paged list applies, so the skip matches the reported page size+ if (pageSize <= 0)+ pageSize = 1;++ var totalCount = await CountAsync(query, cancellationToken);+ var items = await ToListAsync(query.Skip(pageIndex * pageSize).Take(pageSize), cancellationToken);++ return new PagedList<TResult>(items, pageIndex, pageSize, totalCount);+ }++ #endregion}\ No newline at end of filediff --git a/src/Core/Grand.Domain/PagedList.cs b/src/Core/Grand.Domain/PagedList.csindex a50031d64..28d0ab3fc 100644--- a/src/Core/Grand.Domain/PagedList.cs+++ b/src/Core/Grand.Domain/PagedList.cs@@ -52,32 +52,4 @@ public class PagedList<T> : List<T>, IPagedList<T>AddRange(source);}- private Task InitializeAsync(IQueryable<T> source, int pageIndex, int pageSize, int? totalCount = null)- {- ArgumentNullException.ThrowIfNull(source);- if (pageSize <= 0)- pageSize = 1;-- TotalCount = totalCount ?? source.Count();- source = totalCount == null ? source.Skip(pageIndex * pageSize).Take(pageSize) : source;- AddRange(source);-- if (pageSize > 0)- {- TotalPages = TotalCount / pageSize;- if (TotalCount % pageSize > 0)- TotalPages++;- }-- PageSize = pageSize;- PageIndex = pageIndex;- return Task.CompletedTask;- }-- public static async Task<PagedList<T>> Create(IQueryable<T> source, int pageIndex, int pageSize)- {- var pagelist = new PagedList<T>();- await pagelist.InitializeAsync(source, pageIndex, pageSize);- return pagelist;- }}\ No newline at end of filediff --git a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.csindex 3fea1f3df..737616e99 100644--- a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs+++ b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs@@ -46,12 +46,12 @@ public class ShippingByWeightService : IShippingByWeightServicepublic virtual async Task<IPagedList<ShippingByWeightRecord>> GetAll(int pageIndex = 0, int pageSize = int.MaxValue){var key = string.Format(SHIPPINGBYWEIGHT_ALL_KEY, pageIndex, pageSize);- return await _cacheBase.GetAsync(key, () =>+ return await _cacheBase.GetAsync(key, async () =>{var query = from sbw in _sbwRepository.Tableselect sbw;- return Task.FromResult(new PagedList<ShippingByWeightRecord>(query, pageIndex, pageSize));+ return await _sbwRepository.PagedAsync(query, pageIndex, pageSize);});}diff --git a/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs b/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.csindex b7922872b..f361e32d9 100644--- a/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs+++ b/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs@@ -83,7 +83,7 @@ public class TaxRateService : ITaxRateService.OrderBy(tr => tr.StoreId).ThenBy(tr => tr.CountryId).ThenBy(tr => tr.StateProvinceId).ThenBy(tr => tr.Zip).ThenBy(tr => tr.TaxCategoryId);- return await Task.FromResult(new PagedList<TaxRate>(ordered, pageIndex, pageSize));+ return await _taxRateRepository.PagedAsync(ordered, pageIndex, pageSize);});}diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.csindex 152491ba3..ee12c930a 100644--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs@@ -232,7 +232,7 @@ public class CustomerServiceTestsAssert.IsNull(result);}- [DataTestMethod]+ [TestMethod][DataRow("")][DataRow(" ")]public async Task GetCustomerByEmail_EmptyOrWhitespaceEmail_ReturnsNull(string email)diff --git a/src/Tests/Grand.Data.Tests/MongoDb/MongoQueryableContractTests.cs b/src/Tests/Grand.Data.Tests/MongoDb/MongoQueryableContractTests.csnew file mode 100644index 000000000..024dae9e5--- /dev/null+++ b/src/Tests/Grand.Data.Tests/MongoDb/MongoQueryableContractTests.cs@@ -0,0 +1,85 @@+using Grand.Data.Mongo;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using MongoDB.Driver;++namespace Grand.Data.Tests.MongoDb;++/// <summary>+/// <see cref="MongoRepository{T}" /> executes whatever query it is handed straight on the driver, with no check+/// that the query is still server side. That is only safe because every shape the services compose on top of+/// <see cref="IRepository{T}.Table" /> stays a driver query - projections, groupings and sub-collection+/// flattening included. These tests pin that assumption: if a driver upgrade breaks one of them, the matching+/// service starts throwing instead of quietly materialising the whole collection.+/// </summary>+[TestClass]+public class MongoQueryableContractTests+{+ private IRepository<SampleCollection> _repository;++ [TestInitialize]+ public void Init()+ {+ _repository = new MongoDBRepositoryTest<SampleCollection>();+ }++ private static void AssertServerSide<T>(IQueryable<T> query)+ {+ Assert.IsInstanceOfType<IAsyncCursorSource<T>>(query);+ }++ [TestMethod]+ public void Table_StaysServerSide()+ {+ AssertServerSide(_repository.Table);+ }++ [TestMethod]+ public void FilterSortPage_StaysServerSide()+ {+ AssertServerSide(_repository.Table.Where(x => x.Count > 0).OrderBy(x => x.Name).Skip(10).Take(10));+ }++ [TestMethod]+ public void ProjectionToScalar_StaysServerSide()+ {+ AssertServerSide(_repository.Table.Select(x => x.Name));+ }++ /// <summary>Shape used by CustomerReportService.GetBestCustomersReport.</summary>+ [TestMethod]+ public void GroupingToAnonymousType_StaysServerSide()+ {+ var grouped = from item in _repository.Table+ group item by item.Name+ into g+ select new { Name = g.Key, Total = g.Sum(x => x.Count), Lines = g.Count() };++ AssertServerSide(grouped.OrderByDescending(x => x.Total));+ }++ /// <summary>Shape used by ProductCategoryService and ProductCollectionService.</summary>+ [TestMethod]+ public void FlattenedSubCollection_StaysServerSide()+ {+ var flattened = from sample in _repository.Table+ from category in sample.Category+ select new { sample.Id, category.Name, category.DisplayOrder };++ AssertServerSide(flattened.Where(x => x.DisplayOrder > 0).OrderBy(x => x.DisplayOrder));+ }++ /// <summary>Shape used by OrderReportService - the closure list is sent as a filter, not enumerated locally.</summary>+ [TestMethod]+ public void FilterAgainstInMemoryList_StaysServerSide()+ {+ var excluded = new List<string> { "a", "b" };++ AssertServerSide(_repository.Table.Where(x => !excluded.Contains(x.Id)));+ }++ [TestMethod]+ public void PlainLinqToObjects_IsNotServerSide()+ {+ Assert.IsNotInstanceOfType<IAsyncCursorSource<SampleCollection>>(new List<SampleCollection>().AsQueryable());+ }+}diff --git a/src/Tests/Grand.Data.Tests/RepositoryPagedQueryTests.cs b/src/Tests/Grand.Data.Tests/RepositoryPagedQueryTests.csnew file mode 100644index 000000000..fd9ebc3b3--- /dev/null+++ b/src/Tests/Grand.Data.Tests/RepositoryPagedQueryTests.cs@@ -0,0 +1,182 @@+using Grand.Data.Tests.LiteDb;+using Grand.Data.Tests.MongoDb;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace Grand.Data.Tests;++/// <summary>+/// Covers the query execution primitives on <see cref="IRepository{T}" />. The paging arithmetic has to stay+/// identical to what the paged list produced before execution moved out of the domain project, so every+/// assertion here is on TotalCount / TotalPages / page contents rather than on how the query ran.+/// </summary>+[TestClass]+public class RepositoryPagedQueryTests+{+ private const string Mongo = "MongoDB";+ private const string LiteDb = "LiteDB";++ private IRepository<SampleCollection> _liteDb;+ private IRepository<SampleCollection> _mongoRepository;++ [TestInitialize]+ public async Task Init()+ {+ _mongoRepository = new MongoDBRepositoryTest<SampleCollection>();+ _liteDb = new LiteDBRepositoryMock<SampleCollection>();++ foreach (var repository in new[] { _mongoRepository, _liteDb })+ for (var i = 1; i <= 25; i++)+ await repository.InsertAsync(new SampleCollection { Name = $"sample {i:00}", Count = i });+ }++ private IRepository<SampleCollection> Repository(string provider)+ {+ return provider == Mongo ? _mongoRepository : _liteDb;+ }++ [TestMethod]+ [DataRow(Mongo)]+ [DataRow(LiteDb)]+ public async Task PagedAsync_FirstPage_ReturnsPageAndTotals(string provider)+ {+ var repository = Repository(provider);+ var query = repository.Table.OrderBy(x => x.Count);++ var result = await repository.PagedAsync(query, 0, 10);++ Assert.AreEqual(25, result.TotalCount);+ Assert.AreEqual(3, result.TotalPages);+ Assert.AreEqual(0, result.PageIndex);+ Assert.AreEqual(10, result.PageSize);+ Assert.AreEqual(10, result.Count);+ Assert.AreEqual(1, result.First().Count);+ Assert.IsFalse(result.HasPreviousPage);+ Assert.IsTrue(result.HasNextPage);+ }++ [TestMethod]+ [DataRow(Mongo)]+ [DataRow(LiteDb)]+ public async Task PagedAsync_LastPartialPage_ReturnsRemainder(string provider)+ {+ var repository = Repository(provider);+ var query = repository.Table.OrderBy(x => x.Count);++ var result = await repository.PagedAsync(query, 2, 10);++ Assert.AreEqual(25, result.TotalCount);+ Assert.AreEqual(5, result.Count);+ Assert.AreEqual(21, result.First().Count);+ Assert.IsTrue(result.HasPreviousPage);+ Assert.IsFalse(result.HasNextPage);+ }++ [TestMethod]+ [DataRow(Mongo)]+ [DataRow(LiteDb)]+ public async Task PagedAsync_PageBeyondRange_ReturnsEmptyPageWithTotals(string provider)+ {+ var repository = Repository(provider);+ var query = repository.Table.OrderBy(x => x.Count);++ var result = await repository.PagedAsync(query, 99, 10);++ Assert.AreEqual(0, result.Count);+ Assert.AreEqual(25, result.TotalCount);+ Assert.AreEqual(3, result.TotalPages);+ }++ [TestMethod]+ [DataRow(Mongo)]+ [DataRow(LiteDb)]+ public async Task PagedAsync_NoMatches_ReturnsEmpty(string provider)+ {+ var repository = Repository(provider);+ var query = repository.Table.Where(x => x.Count > 1000);++ var result = await repository.PagedAsync(query, 0, 10);++ Assert.AreEqual(0, result.Count);+ Assert.AreEqual(0, result.TotalCount);+ Assert.AreEqual(0, result.TotalPages);+ }++ [TestMethod]+ [DataRow(Mongo)]+ [DataRow(LiteDb)]+ public async Task PagedAsync_NonPositivePageSize_NormalizesToOne(string provider)+ {+ var repository = Repository(provider);+ var query = repository.Table.OrderBy(x => x.Count);++ var result = await repository.PagedAsync(query, 0, 0);++ Assert.AreEqual(1, result.PageSize);+ Assert.AreEqual(1, result.Count);+ Assert.AreEqual(25, result.TotalPages);+ }++ [TestMethod]+ [DataRow(Mongo)]+ [DataRow(LiteDb)]+ public async Task PagedAsync_Projection_ReturnsProjectedPage(string provider)+ {+ var repository = Repository(provider);+ var query = repository.Table.OrderBy(x => x.Count).Select(x => x.Name);++ var result = await repository.PagedAsync(query, 0, 5);++ Assert.AreEqual(25, result.TotalCount);+ Assert.AreEqual(5, result.Count);+ Assert.AreEqual("sample 01", result.First());+ }++ [TestMethod]+ [DataRow(Mongo)]+ [DataRow(LiteDb)]+ public async Task ToListAsync_ReturnsAllMatches(string provider)+ {+ var repository = Repository(provider);++ var result = await repository.ToListAsync(repository.Table.Where(x => x.Count <= 3));++ Assert.AreEqual(3, result.Count);+ }++ [TestMethod]+ [DataRow(Mongo)]+ [DataRow(LiteDb)]+ public async Task CountAsync_ReturnsNumberOfMatches(string provider)+ {+ var repository = Repository(provider);++ Assert.AreEqual(3, await repository.CountAsync(repository.Table.Where(x => x.Count <= 3)));+ }++ [TestMethod]+ [DataRow(Mongo)]+ [DataRow(LiteDb)]+ public async Task PagedAsync_NullQuery_Throws(string provider)+ {+ var repository = Repository(provider);++ await Assert.ThrowsExactlyAsync<ArgumentNullException>(() =>+ repository.PagedAsync<SampleCollection>(null, 0, 10));+ }++ /// <summary>+ /// Handing the Mongo repository a sequence that is already in memory is a programming error - it means the+ /// caller materialised the query before the repository could run it, which is the blocking pattern these+ /// methods exist to remove. It has to fail loudly rather than quietly enumerate and look like it worked.+ /// </summary>+ [TestMethod]+ public async Task MongoRepository_InMemoryQuery_ThrowsInsteadOfEnumerating()+ {+ var items = Enumerable.Range(1, 25).Select(i => new SampleCollection { Count = i }).ToList();++ await Assert.ThrowsExactlyAsync<ArgumentException>(() =>+ _mongoRepository.ToListAsync(items.AsQueryable().Where(x => x.Count <= 4)));+ await Assert.ThrowsExactlyAsync<ArgumentException>(() =>+ _mongoRepository.PagedAsync(items.AsQueryable().OrderBy(x => x.Count), 0, 10));+ }+}diff --git a/src/Web/Grand.Web.Admin/Controllers/MaintenanceController.cs b/src/Web/Grand.Web.Admin/Controllers/MaintenanceController.csindex e083dc097..2f0d82661 100644--- a/src/Web/Grand.Web.Admin/Controllers/MaintenanceController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/MaintenanceController.cs@@ -123,7 +123,7 @@ public class MaintenanceController : BaseAdminControllervar numberOfConvertItems = 0;if (storageSettings.PictureStoreInDb){- var pictures = pictureService.GetPictures();+ var pictures = await pictureService.GetPictures();foreach (var picture in pictures)try{diff --git a/src/Web/Grand.Web.Admin/Controllers/SettingController.cs b/src/Web/Grand.Web.Admin/Controllers/SettingController.csindex 321b657be..1fcaf63df 100644--- a/src/Web/Grand.Web.Admin/Controllers/SettingController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/SettingController.cs@@ -936,7 +936,7 @@ public class SettingController(const int pageSize = 100;while (true){- var pictures = pictureService.GetPictures(pageIndex, pageSize);+ var pictures = await pictureService.GetPictures(pageIndex, pageSize);pageIndex++;if (!pictures.Any())break;diff --git a/src/Web/Grand.Web.AdminShared/Services/CustomerReportViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/CustomerReportViewModelService.csindex a20517609..72813b9e3 100644--- a/src/Web/Grand.Web.AdminShared/Services/CustomerReportViewModelService.cs+++ b/src/Web/Grand.Web.AdminShared/Services/CustomerReportViewModelService.cs@@ -122,7 +122,7 @@ public class CustomerReportViewModelService : ICustomerReportViewModelServicevar paymentStatus = model.PaymentStatusId > 0 ? (PaymentStatus?)model.PaymentStatusId : null;var shippingStatus = model.ShippingStatusId > 0 ? (ShippingStatus?)model.ShippingStatusId : null;- var items = _customerReportService.GetBestCustomersReport(+ var items = await _customerReportService.GetBestCustomersReport(model.StoreId,createdFromUtc: startDateValue,createdToUtc: endDateValue,diff --git a/src/Web/Grand.Web.Vendor/Controllers/ReportsController.cs b/src/Web/Grand.Web.Vendor/Controllers/ReportsController.csindex 6e2133656..50fa108a1 100644--- a/src/Web/Grand.Web.Vendor/Controllers/ReportsController.cs+++ b/src/Web/Grand.Web.Vendor/Controllers/ReportsController.cs@@ -357,7 +357,7 @@ public class ReportsController : BaseVendorControllervar paymentStatus = model.PaymentStatusId > 0 ? (PaymentStatus?)model.PaymentStatusId : null;- var items = _customerReportService.GetBestCustomersReport("", _contextAccessor.WorkContext.CurrentVendor.Id, startDateValue,+ var items = await _customerReportService.GetBestCustomersReport("", _contextAccessor.WorkContext.CurrentVendor.Id, startDateValue,endDateValue,null, paymentStatus, null, 2, command.Page - 1, command.PageSize);