簡體   English   中英

父對象和子對象的集合

[英]Parent and collection of child objects

假設我有一個Customer類和一個Invoice類。 Customer包含一個名為InvoicesList<Invoice>屬性。 可以用單個Linq語句填充嗎? 還是我需要先選擇客戶,然后對他們進行一次foreach以便以后提取發票?

就像是:

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

我不能在那里選擇客戶,或者內部列表沒有填寫。 也許一group呢?

編輯:這有效。 只是想知道是否有其他方式

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

如果要從數據庫加載並嘗試加載集合,則可以使用.Include()方法顯式加載集合。 如果您在關閉與數據庫的連接后嘗試訪問集合,則將收到錯誤消息。

您應該使用以下內容:

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

這是不可能的。 解決方法是使用let子句,如OP的Edit區域所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM