2008-12-09 113 views
2

我需要對來自數據庫表(期間)的時間段和來自表(發票)中發票列表的期間的開始和結束日期執行LINQ查詢。這兩張表之間沒有關鍵的參考,我怎麼做發票子查詢?LINQ子查詢

我試圖做類似下面的內容:

var query = (from p in db.DataContext.Periods 
      // Subquery i in db.DataContext.Invoices 
      let InvoiceAmount = i.Where(t => t.InvoiceDate >= p.StartDate && t.InvoiceDate <= p.EndDate) 
      select new PeriodView 
      (
       p.Name, 
       p.StartDate, 
       p.EndDate, 
       InvoiceAmount.Count() 
      )); 

回答

4
var periodViewList = 
    (from p in db.DataContext.Periods 
    select new PeriodView(
     p.Name, 
     p.StartDate, 
     p.EndDate, 
     db.DataContext.Invoices.Where(i => i.InvoiceDate >= p.StartDate && i.InvoiceDate <= p.EndDate).Count() 
    )).ToList(); 

我假設PeriodView構造看起來像這樣

public PeriodView (string name, DateTime startDate, DateTime endDate, int invoiceCount) { 
... 
} 
+0

只是要清楚,這將發出N + 1個查詢,其中N是期數。 +1 – 2008-12-09 04:18:36