2016-10-18 11 views
1

Linq文でWhere句として使用される4つの共通要素(startDate、endDate、CompanyID、StoreID)を共有するダッシュボードを作成しました。同じLinq結果に対して複数のLinqクエリを実行する

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

I:その文の結果は、その後、ここでは、現在起こっているの重複を示すための短いsnippitあるグループにさまざまな方法で照会し、データをソートし、チャート、リストなどに使用されていますダッシュボード上でこれらの呼び出しの15のようなしていると私は想像しているときから非常に遅くなることができます複数の呼び出しが実際には、データベースは一度問い合わせる必要がある結果は異なる結果を照会する必要があります。

どうすればいいですか?

すべてのヘルプは大幅に各クエリが同じデータに、separatly実行あなたの現在のソリューションでは

答えて

2

をいただければ幸いです。まず、クエリの共有部分を実行し、データベースから結果を取得することができます。あなたが効率的に行うことができます

//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

ありがとうございますこれはもっと意味があります。 – Nate58

+0

@NateGreene - あなたは歓迎です:)あなたは、 'Where'関数に' && '演算子を使って' where'条件をすべて入れることもできます。全く同じSQLに変換されますが、少しきれいに見えるかもしれません –

+1

エンティティ・フレームワーク・タスクを単一のコンテキストに対して並列に実行することはできません。非同期/待機待ちのタスクを使用してメモリエンティティでクエリを実行しても、何も得られません。 –

0

この方法:あなたの例では、今、このデータは、あなたがメモリ内の集計の残りの部分を行うことができます欲しいものだけにフィルタリングされていることこれらwhere条件

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

です。これにより、クエリがデータベース内で1回実行され、残りの部分がメモリデータの引き抜きに発生します。

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