如何获得更好的过滤数据性能查询结果

时间:2018-08-20 21:25:01

标签: c# performance entity-framework

我的查询需要按某些搜索条件过滤大量数据。

搜索是通过3个表进行的:产品,ProductPrimaryCodes,ProductCodes。

在ProductCodes表中设置了大数据(给定大约2000条记录,所以不是那么大,但是由其他表数据最大)。

这是我所做的事的一个例子。

x_df <- data.frame(stringsAsFactors=FALSE,
          ID = c("ID-1", "ID-2", "ID-2", "ID-3", "ID-4", "ID-5"),
         DOB = c("4/16/1955", "9/4/1976", "9/4/1976", "4/16/1955", "2/10/1995",
                 "11/29/1980")
)

查询执行的时间约为8-9秒,因此我认为这种搜索的时间很长。仅需注意,不执行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, }); ,查询将在不到一秒钟的时间内执行并将结果检索到页面。

ProductCodes表:

ProductCodes.Any()

任何建议如何获得更好的查询性能?

1 个答案:

答案 0 :(得分:0)

这是对我有用的解决方案。

        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)

显然不是最干净的,但是我还将考虑为这种查询引入存储过程。