Logo

dev-resources.site

for different kinds of informations.

Check Pagination in .NET: With and Without Entity Framework

Published at
10/17/2024
Categories
dotnet
pagination
entityframework
csharp
Author
dotnetfullstackdev
Author
18 person written this
dotnetfullstackdev
open
Check Pagination in .NET: With and Without Entity Framework

Pagination refers to the process of dividing a large dataset into smaller, manageable chunks, which can be fetched and displayed incrementally. This technique is essential for improving application performance and user experience, especially when dealing with large datasets.

📌Explore more at: https://dotnet-fullstack-dev.blogspot.com/
🌟 Sharing would be appreciated! 🚀

Pagination with Entity Framework

Entity Framework (EF) simplifies database interactions in .NET applications by allowing developers to work with data using .NET objects. Here’s how you can implement pagination using EF.

Step 1. Setting Up the Project.

Assuming you have a .NET project set up with EF, let’s first create a simple model and DbContext.

Product.cs

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

ApplicationDbContext.cs

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2. Implementing Pagination Logic.

You can implement pagination using the Skip and Take methods provided by LINQ.

ProductService.cs

public class ProductService
{
    private readonly ApplicationDbContext _context;

    public ProductService(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<List<Product>> GetPaginatedProducts(int pageNumber, int pageSize)
    {
        return await _context.Products
            .Skip((pageNumber - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();
    }
}
Enter fullscreen mode Exit fullscreen mode

ProductsController.cs

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly ProductService _productService;

    public ProductsController(ProductService productService)
    {
        _productService = productService;
    }

    [HttpGet]
    public async Task<IActionResult> Get(int pageNumber = 1, int pageSize = 10)
    {
        var products = await _productService.GetPaginatedProducts(pageNumber, pageSize);
        return Ok(products);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3. Configuring Dependency Injection.

Register your DbContext and ProductService in Program.cs.

Program.cs

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<ProductService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.Run();
Enter fullscreen mode Exit fullscreen mode

Pagination Without Entity Framework

If you are not using EF, you can still implement pagination using plain ADO.NET or any other data access technique.

Step 1. Setting Up the Data Access Layer.

Product.cs

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

ProductRepository.cs

using System.Data;
using System.Data.SqlClient;

public class ProductRepository
{
    private readonly string _connectionString;

    public ProductRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public List<Product> GetPaginatedProducts(int pageNumber, int pageSize)
    {
        var products = new List<Product>();

        using (var connection = new SqlConnection(_connectionString))
        {
            var command = new SqlCommand("sp_GetPaginatedProducts", connection)
            {
                CommandType = CommandType.StoredProcedure
            };
            command.Parameters.AddWithValue("@PageNumber", pageNumber);
            command.Parameters.AddWithValue("@PageSize", pageSize);

            connection.Open();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    products.Add(new Product
                    {
                        Id = Convert.ToInt32(reader["Id"]),
                        Name = reader["Name"].ToString(),
                        Price = Convert.ToDecimal(reader["Price"])
                    });
                }
            }
        }

        return products;
    }
}
Enter fullscreen mode Exit fullscreen mode

sp_GetPaginatedProducts (SQL Stored Procedure)

CREATE PROCEDURE sp_GetPaginatedProducts
    @PageNumber INT,
    @PageSize INT
AS
BEGIN
    SET NOCOUNT ON;

    SELECT Id, Name, Price
    FROM Products
    ORDER BY Id
    OFFSET (@PageNumber - 1) * @PageSize ROWS
    FETCH NEXT @PageSize ROWS ONLY;
END
Enter fullscreen mode Exit fullscreen mode

Step 2. Implementing the Service and Controller.

ProductService.cs

public class ProductService
{
    private readonly ProductRepository _productRepository;

    public ProductService(ProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    public List<Product> GetPaginatedProducts(int pageNumber, int pageSize)
    {
        return _productRepository.GetPaginatedProducts(pageNumber, pageSize);
    }
}
Enter fullscreen mode Exit fullscreen mode

ProductsController.cs

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly ProductService _productService;

    public ProductsController(ProductService productService)
    {
        _productService = productService;
    }

    [HttpGet]
    public IActionResult Get(int pageNumber = 1, int pageSize = 10)
    {
        var products = _productService.GetPaginatedProducts(pageNumber, pageSize);
        return Ok(products);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3. Configuring Dependency Injection.

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSingleton(new ProductRepository(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<ProductService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.Run();
Enter fullscreen mode Exit fullscreen mode

Conclusion

Pagination is a critical feature for applications dealing with large datasets. This blog demonstrated how to implement pagination in a C#.NET application both with and without Entity Framework. While EF simplifies many tasks, using ADO.NET or other data access techniques provides greater control. Choose the approach that best fits your application’s needs and architecture.

entityframework Article's
30 articles in total
Favicon
Entity Framework Core Code First
Favicon
Code First Approach with Entity Framework.
Favicon
Custom NET8 Entity Framework Core Generic Repository
Favicon
Link Many To Many entities with shadow join-table using Entity Framework Core
Favicon
Running Entity Framework Core Migrations with Optimizely CMS 12
Favicon
Check Pagination in .NET: With and Without Entity Framework
Favicon
EF Core 6 - correct types halving the execution time!
Favicon
EF Core 6 - This SqlTransaction has completed; it is no longer usable.
Favicon
Entity Framework Core Tutorial:Introduction to Entity Framework Core
Favicon
ReadOnly DbContext with Entity Framework
Favicon
[KOSD] Multiple Parallel Operations in Entity Framework Core (.NET 8)
Favicon
Entity Framework in .net core 6.0 - Code first and Database first approach
Favicon
5 EF Core Features You Need To Know
Favicon
C# | Best Practices for Pagination using EF Core 8
Favicon
C# | Using Entity Framework with PostgreSQL Database
Favicon
C# | Entity Framework Generic Repository with SOLID Design Pattern
Favicon
C# | Entity Framework Issues and Troubleshooting
Favicon
Entity Framework Core with Scalar Functions
Favicon
Prefer Empty Objects over Compiler tricks
Favicon
The Differences Between EntityFramework .Add and .AddAsync
Favicon
Entity FrameWork
Favicon
Load Appointments on Demand in Blazor Scheduler using Entity Framework Core
Favicon
Finding the Right Balance: Clean Architecture and Entity Framework in Practice
Favicon
Compilation steps in EF Core
Favicon
Learning is another full-time job.
Favicon
How To Use EF Core Interceptors
Favicon
Using Entity Framework Core 8 Owned Types HasData()
Favicon
Simple Event-Sourcing with EF Core and SQL Server
Favicon
Delete in EF 8 !
Favicon
Optimizing Database Access with Entity Framework - Lazy Loading vs. Eager Loading

Featured ones: