简体   繁体   中英

Parent and collection of child objects

Say I have a Customer class and an Invoice class. Customer contains a List<Invoice> property called Invoices . Can this be filled with a single Linq statement? Or do I need to select customers first and then do a foreach on them to pull invoices later?

Something like:

(from customer in customers
 join invoice in invoices on customer.Id = invoice.CustomerId
 select <what>?

I can't select a customer there or the inner list isn't filled. Maybe a group instead?

Edit: This works. Just wondering if there was a different way

var customersWithInvoices =
   (from customer in customers
    let invoiceGroup = (from invoice in invoices where invoice.CustomerId == customer.Id select invoice).ToList()
    select new { customer, invoiceGroup }).ToList();

foreach (var obj in customersWithInvoices) {
   obj.customer.Invoices = obj.invoiceGroup;
   CustomerList.Add(obj.customer);
}

If you are loading from a database and are trying to load a collection you can use the .Include() method to explicitly load the collection. If you try to access the collection after your connection to the database has closed then you will recieve an error.

You should use the following:

using(var context = new ServiceContext())
{
  var customers = context.CustomerSet.Include(cust => cust.Invoices);
}

This isn't possible. The work around is to use the let clause as shown in the Edit area of the OP:

var customersWithInvoices =
   (from customer in customers
    let invoiceGroup = (from invoice in invoices where invoice.CustomerId == customer.Id select invoice).ToList()
    select new { customer, invoiceGroup }).ToList();

foreach (var obj in customersWithInvoices) {
   obj.customer.Invoices = obj.invoiceGroup;
   CustomerList.Add(obj.customer);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM