子对象的父对象和集合
Parent and collection of child objects
假设我有一个 Customer
class 和一个 Invoice
class。 Customer
包含一个名为 Invoices
的 List<Invoice>
属性。这可以用单个 Linq
语句填充吗?还是我需要先 select 客户,然后对他们做 foreach
以稍后提取发票?
类似于:
(from customer in customers
join invoice in invoices on customer.Id = invoice.CustomerId
select <what>?
我不能 select 那里有客户,或者内部列表未填写。也许 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 的编辑区域所示:
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);
}
假设我有一个 Customer
class 和一个 Invoice
class。 Customer
包含一个名为 Invoices
的 List<Invoice>
属性。这可以用单个 Linq
语句填充吗?还是我需要先 select 客户,然后对他们做 foreach
以稍后提取发票?
类似于:
(from customer in customers
join invoice in invoices on customer.Id = invoice.CustomerId
select <what>?
我不能 select 那里有客户,或者内部列表未填写。也许 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 的编辑区域所示:
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);
}