在 .NET 中,分页查询通常使用 Entity Framework 或 ADO.NET 来实现。以下是一个简单的示例代码,展示如何使用 Entity Framework 进行分页查询:,,“
csharp,using System;,using System.Linq;,using Microsoft.EntityFrameworkCore;,,public class Program,{, public static void Main(), {, using (var context = new MyDbContext()), {, int pageNumber = 1; // 当前页码, int pageSize = 10; // 每页显示的记录数,, var query = context.MyEntities, .OrderBy(e => e.Id), .Skip((pageNumber 1) * pageSize), .Take(pageSize);,, foreach (var entity in query), {, Console.WriteLine(entity.Name);, }, }, },},`,,在这个示例中,MyDbContext 是你的数据库上下文类,MyEntities 是你要查询的实体集。通过 OrderBy 方法对数据进行排序,然后使用 Skip 和 Take` 方法实现分页功能。.NET 分页查询代码

在现代的Web应用开发中,分页查询是一个常见的需求,分页查询不仅可以提高系统的性能,还可以增强用户体验,本文将详细介绍如何在.NET框架下实现分页查询,并提供完整的代码示例。
环境准备
在开始编写代码之前,我们需要确保开发环境已经安装好以下工具和库:
1、Visual Studio
2、.NET SDK
3、Entity Framework Core
4、SQL Server(或其他支持的数据库)
数据库设计
假设我们有一个名为Products的表,其结构如下:

CREATE TABLE Products (
Id INT PRIMARY KEY,
Name NVARCHAR(50),
Price DECIMAL(10, 2),
Category NVARCHAR(50)
);
实体类
我们需要定义一个与数据库表对应的实体类。
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
数据上下文
我们需要创建一个数据上下文类来管理数据库操作。
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Your_Connection_String");
}
}
分页查询方法
为了实现分页查询,我们需要编写一个通用的分页查询方法,这个方法将接受页码和每页记录数作为参数,并返回当前页的数据以及总记录数。
public class PaginatedList<T>
{
public List<T> Items { get; set; }
public int PageIndex { get; set; }
public int TotalCount { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
Items = items;
TotalCount = count;
PageIndex = pageIndex;
PageSize = pageSize;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
}
}
public static class PaginationHelper
{
public static async Task<PaginatedList<T>> GetPagedDataAsync<T>(this DbSet<T> dbSet, int pageIndex, int pageSize) where T : class
{
var count = await dbSet.CountAsync();
var items = await dbSet.Skip((pageIndex 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}
使用分页查询方法
现在我们可以在我们的服务或控制器中使用这个分页查询方法了。
public class ProductService
{
private readonly AppDbContext _context;
public ProductService(AppDbContext context)
{
_context = context;
}
public async Task<PaginatedList<Product>> GetProductsAsync(int pageIndex, int pageSize)
{
return await _context.Products.GetPagedDataAsync(pageIndex, pageSize);
}
}
控制器示例
我们在控制器中使用这个服务来处理HTTP请求。
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly ProductService _productService;
public ProductsController(ProductService productService)
{
_productService = productService;
}
[HttpGet]
public async Task<IActionResult> GetProducts(int pageIndex = 1, int pageSize = 10)
{
var products = await _productService.GetProductsAsync(pageIndex, pageSize);
return Ok(products);
}
}
单元测试
为了确保我们的分页查询功能正常工作,我们可以编写单元测试。
using Xunit;
using FluentAssertions;
using Moq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
public class ProductServiceTests
{
[Fact]
public async Task GetProductsAsync_ShouldReturnCorrectData()
{
var options = new DbContextOptionsBuilder<AppDbContext>().Options;
using var context = new AppDbContext(options);
context.Products.AddRange(new List<Product> { /* Add some test data */ });
await context.SaveChangesAsync();
var service = new ProductService(context);
var result = await service.GetProductsAsync(1, 10);
result.Items.Count.Should().Be(10); // Assuming there are at least 10 records in the database for testing purposes
}
}
通过上述步骤,我们已经成功地在.NET框架下实现了分页查询功能,这不仅提高了系统的性能,还改善了用户体验,希望本文对你有所帮助!

相关问题与解答
问题1:如何更改每页显示的记录数?
解答:你可以通过修改控制器中的默认参数值来更改每页显示的记录数,将默认值从10改为20:
[HttpGet]
public async Task<IActionResult> GetProducts(int pageIndex = 1, int pageSize = 20) // Changed from 10 to 20
{
var products = await _productService.GetProductsAsync(pageIndex, pageSize);
return Ok(products);
}
这样,每次调用API时都会返回20条记录,而不是10条。
问题2:如何处理分页查询中的异常情况?
解答:在实际应用中,我们应该处理可能出现的各种异常情况,例如数据库连接失败、查询超时等,你可以在服务层添加异常处理逻辑,并在控制器中捕获这些异常并返回适当的HTTP状态码。
[HttpGet]
public async Task<IActionResult> GetProducts(int pageIndex = 1, int pageSize = 10)
{
try
{
var products = await _productService.GetProductsAsync(pageIndex, pageSize);
return Ok(products);
}
catch (Exception ex) when (ex is DbUpdateException || ex is DbConnectionException) // Example exceptions to handle
{
// Log error details here (ex.Message, etc.)
return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "An unexpected error occurred.");
}
}
来源互联网整合,作者:小编,如若转载,请注明出处:https://www.aiboce.com/ask/104397.html