tags:

views:

1117

answers:

1
+1  Q: 

LINQ Subquery

I need to perform a LINQ query for both a time period from a database table (Period) and a list of invoices from a table (Invoice) that fall within the period's start and end dates. There is no key reference between the two tables, how can I do the Invoice subquery?

I am trying to do something similar to the following:

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()
              ));
+3  A: 
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();

I'm assuming that the PeriodView constructor looks something like this

public PeriodView (string name, DateTime startDate, DateTime endDate, int invoiceCount) {
...
}
Strelok
Just to be clear, this will issue N+1 queries, where N is the number of periods. +1
Bryan Watts
Thanks for your help!!
jwarzech