如何在搜索/过滤数据期间处理空字段?

How to handle empty fields during searching / filtering data?

我正在努力使用数据搜索算法,该算法必须使用多个字段从数据库中检索一些数据。每个文本框都提供一个给定的参数,存储在数据库中,由 Entity Framework 访问。当我向所有字段输入数据时它工作正常,但如果我将任何字段留空,它不会检索任何记录。 我的问题是 - 如何处理空字段。如果我留下任何没有数据的字段,在从数据库 selecting 和基于非空参数的 select 数据期间不应该考虑此参数。

这是我目前创建的:

   [HttpPost]
   public ViewResult Search(string brand, string model, int? manufactDateMin,
       int? manufactDateMax, int? priceMin, int? priceMax, int? engineCapMin,
       int? engineCapMax, string engineType, int page = 1)
   {

       IEnumerable<Car> foundItems = repository.Cars
           .Where(c => brand == null || c.Brand == brand)
           .Where(c => model == null || c.Model == model)
           .Where(c => manufactDateMin == null || manufactDateMax == null || (c.ManufactDate.Year >= manufactDateMin) && (c.ManufactDate.Year < manufactDateMax))
           .Where(c => priceMin == null || priceMax == null || (c.Price >= priceMin) && (c.Price < priceMax))
           .Where(c => engineCapMin == null || engineCapMax == null || (c.EngineCapacity >= engineCapMin) && (c.EngineCapacity < engineCapMax))
           .Where(c => engineType == null || c.EngineType == engineType)
           .OrderBy(c => c.Id)
           .Skip(PageSize * (page - 1))
           .Take(PageSize);

       CarListViewModel VMmodel = new CarListViewModel
       {
           Cars = foundItems,
           PagingInfo = new PagingInfo
           {
               CurrentPage = page,
               ItemsPerPage = PageSize,
               TotalItems = foundItems.Count(),
           },
           CarType = null
       };

       return View("List", VMmodel);
   }

不要为每个比较使用新的 where 语句。将它们合二为一。为了便于阅读,将它们分开成一个新行。此外,您的参数被定义为字符串,但您将其与 null 进行比较。您必须传递一个 null 才能使它起作用。如果您要传递文本框或其他内容的内容,则字符串将为 "" 而不是 null。

.Where(c => brand == "" || c.Brand == brand) &&
       (model == "" || c.Model == model) &&
       ((manufactDateMin == null || manufactDateMax == null || (c.ManufactDate.Year >= manufactDateMin) && (c.ManufactDate.Year < manufactDateMax)) &&
       (priceMin == null || priceMax == null || (c.Price >= priceMin) && (c.Price < priceMax))) &&
       (engineCapMin == null || engineCapMax == null || (c.EngineCapacity >= engineCapMin) && (c.EngineCapacity < engineCapMax))) &&
       (engineType == "" || c.EngineType == engineType))

我觉得你应该像这样分开做

IQueryable<Car> query  = repository.Cars;

if (!string.IsNullOrEmpty(brand))
{
 query = query.Where(x => x.Brand  == brand);
}
if (!string.IsNullOrEmpty(model ))
{
 query = query.Where(x => x.Model == model );
}

在你把所有这些都放在 take 和 skyp 之后,它更快,更易读