2011-10-12 43 views
0

我真的很困惑我需要的報告。截至今天,我的大部分報告都很簡單,所以我能夠輕鬆地做到這一點。但作爲在SQL/DLINQ一個新手,我無法通過以下找到我的方式:如何將5種不同類型的linq查詢合併到一個列中

var closingStock = 
    (from p in session.Query<Product>() 
    select new 
    { 
     p.Id, 
     p.Name, 
     p.Batch, 
     p.Rate, 
     ClosingStock = p.Quantity - p.AllocatedQuantity, 
     p.DivisionId 
    }).ToList(); 

var distributedQuantityAfterPeriod = 
    (from i in session.Query<OutwardInvoiceItem>() 
    where i.ParentInvoice.Date > ToDate 
    select new 
    { 
     Id = i.Product.Id, 
     DistributedAfter = i.Quantity 
    }).ToList(); 

var distributedQuantityInPeriod = 
    (from i in session.Query<OutwardInvoiceItem>() 
    where i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate 
    select new 
    { 
     Id = i.Product.Id, 
     Distributed = i.Quantity 
    }).ToList(); 

var receivedQuantityAfterPeriod = 
    (from i in session.Query<InwardInvoiceItem>() 
    where i.ParentInvoice.Date > ToDate 
    select new 
    { 
     Id = i.Product.Id, 
     ReceivedAfter = i.Quantity 
    }).ToList(); 

var receivedQuantityInPeriod = 
    (from i in session.Query<InwardInvoiceItem>() 
    where i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate 
    select new 
    { 
     Id = i.Product.Id, 
     Received = i.Quantity 
    }).ToList(); 

正如你所看到的,我想建立一個特定日期的庫存移動報告。我遇到以下問題:
1.如何減少五個查詢?可能嗎?
2.我該如何將這些查詢提供的數據合併到一個表中,該表按產品ID進行分組並彙總爲數量相關的列?到目前爲止,我正在使用非常慢的循環。

我用的是什麼:
C#4,NHibernate的,SQLite的

任何幫助將非常高度讚賞。

Regards, Yogesh。

回答

1
  1. 減少往返使用.Future()代替.List()

  2. 讓所有的查詢返回

    group i by i.Id into g 
    select new 
    { 
        Id = g.Key, 
        Quantity = g.Sum(x => x.Quantity) 
    }).Future(); 
    

,做

var alltogether = groupedDistributedQuantityAfterPeriod 
    .Concat(groupedDistributedQuantityInPeriod) 
    .Concate(...); 

from g in alltogether 
group g by g.key into all 
select new 
{ 
    Id = all.Key, 
    Quantity = all.Sum(x => x.Quantity) 
}; 

UPD吃:

可以減少查詢的數量與

from i in session.Query<OutwardInvoiceItem>() 
where (i.ParentInvoice.Date > ToDate) || (i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate) 
select ... 

from i in session.Query<InwardInvoiceItem>() 
where (i.ParentInvoice.Date > ToDate) || (i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate) 
select ... 
+0

非常感謝。我已經想出了使用linq合併所有表的方法。但是使用Future和Concat確實給了我更快的結果。如果沒有關於減少查詢數量的答案,我會選擇你的答案。 – Yogesh

相關問題