GetPagedAsync & GetPaged: Mastering Pagination in Buzruk.GenericRepository
This in-depth guide equips you to conquer large datasets effectively using GetPagedAsync
and GetPaged
methods within Buzruk.GenericRepository. We'll explore their functionalities, delve into various parameters for customized pagination, and provide illustrative examples to solidify your understanding.
Understanding GetPagedAsync (Asynchronous) and GetPaged (Synchronous)
- Core Purpose: Both methods retrieve data in manageable chunks, ideal for pagination and handling large datasets efficiently.
GetPagedAsync
operates asynchronously, maintaining UI responsiveness.Get
works synchronously, fetching a page of data in a single operation.
Unveiling the Powerhouse Parameters
Both methods offer a plethora of optional parameters that empower you to tailor pagination to your specific needs. Here's a breakdown of the key ones:
- Predicates (Expression<Func<T, bool>>):
- Function: Filter entities based on specific criteria before pagination.
- Usage: Pass a lambda expression that evaluates to
true
for entities you want to include in the results.
Example: GetPaged Async: Products with Price Greater Than $100 (Page 2, Size 10)
Task<PagedResult<Product>> pagedProductsTask = repository.GetPagedAsync<Product>(
predicate: p => p.Price > 100,
pageNumber: 2,
pageSize: 10
);
PagedResult<Product> pagedProducts = await pagedProductsTask;
// Access total items and current page's items
int totalItems = pagedProducts.TotalCount;
List<Product> products = pagedProducts.Items;
Console.WriteLine($"Total Products: {totalItems}");
Console.WriteLine($"Products on Page {pageNumber}:");
foreach (var product in products)
{
Console.WriteLine($"- {product.Name}");
}
orderBy
(Expression<Func<T, object>>) andthenBy
(Expression<Func<T, object>>):- Function: Order retrieved entities within a page based on one or more properties.
- Usage: Pass a lambda expression specifying the property for sorting (ascending order by default). Use
thenBy
for chained sorting (optional).
Example: GetPaged (Synchronous): Top 3 Products on Each Page, Ordered by Price (Descending) with thenBy
for Name
var pagedProducts = repository.GetPaged<Product>(
orderBy: p => p.Price descending,
thenBy: p => p.Name,
pageNumber: 1,
pageSize: 3
).ToList(); // Convert to List for easy iteration
foreach (var product in pagedProducts)
{
Console.WriteLine($"Product Name: {product.Name}, Price: ${product.Price}");
}
includes
(Expression<Func<T, object>>[]) andthenInclude
(Expression<Func<T, object>>[]):- Function: Eagerly load related entities along with the primary entities within a page.
- Usage: Pass an array of lambda expressions specifying the navigation properties to include. Use
thenInclude
for nested eager loading (optional).
Example: GetPagedAsync: Get Products with their Categories on Page 1 (Size 5)
Task<PagedResult<Product>> pagedProductsTask = repository.GetPagedAsync<Product>(
includes: p => p.Category,
pageNumber: 1,
pageSize: 5
);
PagedResult<Product> pagedProducts = await pagedProductsTask;
foreach (var product in pagedProducts.Items)
{
Console.WriteLine($"Product Name: {product.Name}");
Console.WriteLine($"Category Name: {product.Category.Name}");
}
tracking
(bool):- Function: Controls whether to track entity changes for potential updates (optional, might require repository configuration for
UpdateAsync
to work). - Usage: Set to
true
to enable change tracking within the retrieved page.
- Function: Controls whether to track entity changes for potential updates (optional, might require repository configuration for
Important Note: Refer to your repository's specific documentation for any additional parameters or configuration requirements related to change tracking.
Behavior Without Parameters
- If no parameters are provided, both
GetPagedAsync
andGetPaged
retrieve the first page (usually page number 1) with a default page size (often configurable). - The returned value is a
PagedResult<T>
object (whereT
is your entity type). This object contains two key properties:
Absolutely! Here's a breakdown of the extension methods provided in the PagedResultsExtension
class
-
GetPage<T>(this PagedResults<T> pagedResults)
- Functionality: This method extracts a specific page of data from the
PagedResults<T>
object. - Parameters:
- pagedResults: The
PagedResults<T>
object containing the paginated data.
- pagedResults: The
- Returns: An
IEnumerable<T>
containing the items for the requested page. - Exception: Throws an
ArgumentOutOfRangeException
if the requested page number is outside the valid range (1 toPageCount
). - Usage:
// Assuming you have a PagedResults<Product> object named 'pagedProducts' IEnumerable<Product> currentPageProducts = pagedProducts.GetPage<Product>(); // Iterate through the products on the current page foreach (var product in currentPageProducts) { Console.WriteLine($"Product Name: {product.Name}"); }
- Functionality: This method extracts a specific page of data from the
-
GetPartialView<T>(this PagedResults<T> model, string controllerName, string actionName, string areaName = "", string routeParameterName = "pageNumber")
- Functionality: This method generates a partial view containing HTML code for page navigation based on the provided PagedResults
model. It leverages Razor syntax (@ symbol) for building the HTML structure. - Parameters:
- model: The PagedResults
instance containing paging information and data. - controllerName: The name of the controller that handles pagination requests.
- actionName: The name of the action method that handles pagination requests.
- areaName (Optional): The name of the area for routing (defaults to empty string).
- routeParameterName (Optional): The name of the route parameter used for the current page number (defaults to "pageNumber").
- model: The PagedResults
- Returns: A string containing the generated HTML partial view for pagination.
- Notes:
- This method currently uses a
StringBuilder
to construct the HTML dynamically. - It includes placeholder comments for functionalities like adding dark mode/light mode options (TODO).
- The logic for generating the pagination links considers various scenarios based on the total number of pages and the current page number.
- It also includes some basic JavaScript code to dynamically set the active page class and handle relative URLs.
- Usage:
- This method currently uses a
- Functionality: This method generates a partial view containing HTML code for page navigation based on the provided PagedResults
// Assuming you have a PagedResults<Product> object named 'pagedProducts'
// and your controller and action names are set
string paginationHtml = pagedProducts.GetPartialView<Product>(
controllerName: "Products",
actionName: "Index"
);
// Use the generated HTML in your Razor view
@Html.Raw(paginationHtml)
Remember:
- The
GetPage
method is useful for retrieving a specific page of data for further processing within your application logic. - The
GetPartialView
method helps in creating a user-friendly pagination interface for navigating through large datasets in your web application. - Consider customizing the provided JavaScript code to fit your specific requirements and styling preferences.