where
子句和逻辑运算符(如
&&
、
||
)来添加多个条件。“
csharp,var results = db.YourEntities.Where(e => e.Property1 == value1 && e.Property2 == value2).ToList();,
“这样可以根据多个条件筛选数据。
在C# MVC中进行多条件查询数据库是一个常见的需求,以下是详细的实现步骤:
需要创建一个与数据库表对应的模型类,假设有一个名为“Products”的表,包含“Id”、“Name”、“Category”、“Price”等字段,可以创建一个如下的模型类:
public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } }
创建一个数据上下文类,用于连接数据库并进行数据库操作,使用Entity Framework Core时,可以通过以下方式创建数据上下文:
public class ApplicationDbContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Your_Connection_String_Here"); } }
将“Your_Connection_String_Here”替换为实际的数据库连接字符串。
1、控制器
在控制器中,创建一个方法来处理多条件查询请求,可以使用LINQ语句根据传入的条件进行筛选。
public class ProductsController : Controller { private readonly ApplicationDbContext _context; public ProductsController(ApplicationDbContext context) { _context = context; } [HttpGet] public async Task<IActionResult> Search(string name, string category, decimal? minPrice, decimal? maxPrice) { var query = _context.Products.AsQueryable(); if (!string.IsNullOrEmpty(name)) { query = query.Where(p => p.Name.Contains(name)); } if (!string.IsNullOrEmpty(category)) { query = query.Where(p => p.Category == category); } if (minPrice.HasValue) { query = query.Where(p => p.Price >= minPrice.Value); } if (maxPrice.HasValue) { query = query.Where(p => p.Price <= maxPrice.Value); } var products = await query.ToListAsync(); return View(products); } }
上述代码中,Search
方法接收多个参数作为查询条件,然后根据这些条件构建查询语句,如果某个条件为空或没有提供,则不会将其添加到查询中。
2、视图
在视图中,显示查询结果,可以使用HTML表格或其他方式展示产品信息。
@model IEnumerable<Product> <table class="table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Category</th> <th>Price</th> </tr> </thead> <tbody> @foreach (var product in Model) { <tr> <td>@product.Id</td> <td>@product.Name</td> <td>@product.Category</td> <td>@product.Price.ToString("C")</td> </tr> } </tbody> </table>
确保在RouteConfig.cs
中正确配置了路由,以便能够访问控制器中的Search
方法。
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } }
假设用户在浏览器中访问/Products/Search?name=Laptop&category=Electronics&minPrice=500&maxPrice=1000
,那么控制器中的Search
方法将会根据这些条件查询数据库,并返回符合条件的产品列表,然后在视图中显示出来。
问题1:如果查询条件较多且复杂,如何优化查询性能?
答:当查询条件较多且复杂时,可以考虑以下优化方法,一是合理使用索引,对于经常用于查询条件的字段,如上述示例中的“Name”、“Category”等,可以在数据库表中创建相应的索引,以提高查询速度,二是避免在查询中使用过多的子查询和复杂的计算,尽量简化查询语句,三是可以使用缓存技术,对于一些不经常变化的查询结果进行缓存,减少数据库的查询次数,四是分析查询执行计划,通过数据库提供的工具分析查询的性能瓶颈,针对性地进行优化。
问题2:如何处理大量数据的分页显示?
答:在处理大量数据的分页显示时,可以在控制器中添加分页逻辑,可以在Search
方法中添加两个参数“page”和“pageSize”,分别表示当前页码和每页显示的记录数,然后使用LINQ的Skip
和Take
方法来实现分页功能,具体代码如下:
[HttpGet] public async Task<IActionResult> Search(string name, string category, decimal? minPrice, decimal? maxPrice, int page = 1, int pageSize = 10) { var query = _context.Products.AsQueryable(); if (!string.IsNullOrEmpty(name)) { query = query.Where(p => p.Name.Contains(name)); } if (!string.IsNullOrEmpty(category)) { query = query.Where(p => p.Category == category); } if (minPrice.HasValue) { query = query.Where(p => p.Price >= minPrice.Value); } if (maxPrice.HasValue) { query = query.Where(p => p.Price <= maxPrice.Value); } var totalRecords = await query.CountAsync(); var products = await query.Skip((page 1) * pageSize).Take(pageSize).ToListAsync(); ViewBag.TotalPages = (int)Math.Ceiling((double)totalRecords / pageSize); ViewBag.CurrentPage = page; return View(products); }
在视图中,需要添加分页导航按钮,以便用户可以切换页面,可以使用HTML的<a>
标签和循环来实现分页导航。
<div> <ul class="pagination"> @for (int i = 1; i <= ViewBag.TotalPages; i++) { <li class="@(i == ViewBag.CurrentPage ? "active" : "")"> <a href="?name=@Request.QueryString["name"]&category=@Request.QueryString["category"]&minPrice=@Request.QueryString["minPrice"]&maxPrice=@Request.QueryString["maxPrice"]&page=@i&pageSize=@ViewBag.pageSize">@i</a> </li> } </ul> </div>
这样就可以实现多条件查询的分页显示功能。