【发布时间】: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