【问题标题】:How to handle empty fields during searching / filtering data?如何在搜索/过滤数据期间处理空字段?
【发布时间】:2019-07-08 19:14:28
【问题描述】:

我正在努力使用数据搜索算法,该算法必须使用多个字段从数据库中检索一些数据。每个文本框提供一个给定的参数,存储在数据库中,由实体框架访问。当我在所有字段中输入数据时它正在工作,但如果我将任何字段留空,它不会检索任何记录。 我的问题是 - 如何处理空字段。如果我留下任何没有数据的字段,在从数据库中选择时不应该考虑这个参数,而是根据非空参数选择数据。

这是我目前创建的:

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

【问题讨论】:

  • 代替variable == null,在字符串中,尽量使用,string.IsNullOrEmpty(variable)

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


【解决方案1】:

不要对每个比较使用新的 where 语句。将它们合二为一。将它们分成一个新行以提高可读性。此外,您的参数被定义为字符串,但您将其与 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))

【讨论】:

  • 我认为多个Where 语句比一个巨大的Where 调用更具可读性。
【解决方案2】:

我觉得你应该这样分开做

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    相关资源
    最近更新 更多