针对相同的Linq结果执行多个Linq查询

时间:2016-10-18 17:09:13

标签: c# performance linq

我创建了一个仪表板,其上显示的所有数据共享4个常用元素(startDate,endDate,CompanyID,StoreID),这些元素在Linq语句中用作Where子句。然后以各种方式查询该语句的结果,对数据进行分组和排序,并在图表,列表等中使用。下面是一个简短的信息,显示当前正在进行的重复:

var dashboardEntity = new BlueStreakSalesDWEntities();

  //Get Total Sales
ViewBag.companySalesTotal = dashboardEntity.FactSales.Where(d => d.DateKey >= startDate)
                                                     .Where(d => d.DateKey <= endDate)
                                                     .Where(c => c.CompanyID == companyID)
                                                     .Sum(a => a.Amount);

//get list of all items sold
var companyStoreTotalItem = dashboardEntity.FactSales.Where(d => d.DateKey >= startDate)
                                           .Where(d => d.DateKey <= endDate)
                                           .Where(c => c.CompanyID == companyID).GroupBy(m => new { m.Description })
                                           .Select(g => new DescriptionAmountModel { Amount = g.Sum(a => a.Amount).Value, Description = g.Key.Description })
                                           .OrderByDescending(x => x.Amount);

我在仪表板上有15个这样的调用,有时候我会想到的是多次调用,实际上只需要查询数据库一次,然后需要查询结果以获得不同的结果。

我该怎么做?

非常感谢任何帮助

2 个答案:

答案 0 :(得分:2)

在当前解决方案中,每个查询在相同数据上分别执行。您可以先执行查询的共享部分,然后从数据库中获取结果。在您的示例中,这些是where条件

//Executes in database
var entities = dashboardEntity.FactSales.Where(d => d.DateKey >= startDate)
                                        .Where(d => d.DateKey <= endDate)
                                        .Where(c => c.CompanyID == companyID)
                                        .ToList();

现在这个数据只被过滤到你想要的内容,你可以在内存中完成其余的聚合:

//Happens in the List<T> in memory
ViewBag.companySalesTotal = entities.Sum(a => a.Amount);

var companyStoreTotalItem = entities.GroupBy(m => new { m.Description })
                                    .Select(g => new DescriptionAmountModel { Amount = g.Sum(a => a.Amount).Value, Description = g.Key.Description })
                                    .OrderByDescending(x => x.Amount);

答案 1 :(得分:0)

这样你就可以提高效率。这使得查询在数据库中执行一次,而部分的其余部分发生在内存数据中的拉出

var result = dashboardEntity.FactSales.Where(d => d.DateKey >= startDate && d => d.DateKey <= endDate && d.CompanyID == companyID).ToList();

ViewBag.companySalesTotal = result.Sum(a => a.Amount); 

//then get list of all items sold from in memory data
var companyStoreTotalItem = result.GroupBy(m => new { m.Description }).Select(g => new DescriptionAmountModel { Amount = g.Sum(a => a.Amount).Value, Description = g.Key.Description }).OrderByDescending(x => x.Amount);