我有一个查询,需要根据一些搜索条件过滤大量数据。
搜索通过3个表进行: Products、ProductPrimaryCodes、ProductCodes。
大数据(假设有大约2000条记录,所以不是很大,但其他表的数据是最大的)集合在ProductCodes表中。
下面是我所做的一个例子。
var result = products.Where(x => x.Code.Contains(se) ||
x.ProductPrimaryCodes.Any(p => p.Code.Contains(se)) ||
x.ProductCodes.Any(p => p.Code.Contains(se)))
.Select(x => new ProductDto
{
Id = x.Id,
Name = x.Name,
InStock = x.InStock,
BrandId = (BrandType)x.BrandId,
Code = x.Code,
CategoryName = x.Category.Name,
SubCategoryName = x.SubCategory.Name,
});查询执行的时间大约是8-9秒,所以我认为对于这种搜索来说是相当长的。需要注意的是,在不执行ProductCodes.Any()的情况下,查询在不到一秒的时间内执行并将结果返回到页面。
ProductCodes表:
Id,
Code,
ProductId如何获得更好的查询性能有什么建议吗?
发布于 2018-08-21 06:51:29
这就是对我有效的解决方案。
var filteredProductsByCode = products.Where(x => x.Code.Contains(se));
var filteredProducts = products.Where(x => x.ProductCodes.Any(p => p.Code.Contains(se))
|| x.ProductPrimaryCodes.Any(p => p.Code.Contains(se)));
return filteredProductsByCode.Union(filteredProducts).Select(x => new ProductDto
{
Id = x.Id,
Name = x.Name,
InStock = x.InStock,
BrandId = (BrandType)x.BrandId,
Code = x.Code,
CategoryName = x.Category.Name,
SubCategoryName = x.SubCategory.Name,
}).OrderByDescending(x => x.Id)显然不是最干净的,但我也会考虑为这类查询引入存储过程。
https://stackoverflow.com/questions/51938695
复制相似问题