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

时间:2019-02-14 17:20:09

标签: c# entity-framework search asp.net-mvc-5

我正在努力寻找数据搜索算法,该算法必须使用多个字段从数据库中检索一些数据。每个文本框都提供一个给定的参数,该参数存储在数据库中,可通过Entity Framework访问。当我在所有字段中输入数据时,它会起作用,但是如果我将任何字段保留为空,则不会检索任何记录。 我的问题是-如何处理空字段。如果我在任何字段中都没有数据,那么在从数据库进行选择并基于非空参数选择数据的过程中,就不要考虑该参数。

这是我到目前为止创建的:

   [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);
   }

2 个答案:

答案 0 :(得分:0)

不要为每个比较使用新的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))

答案 1 :(得分:0)

我认为您应该像这样单独进行

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”之后,它更快,更易读