考虑以下虚构场景:
即使客户没有订购任何产品,我如何为每个客户获取所有类别的列表(不同的或其他的,没关系)?
还假设我们没有导航属性,所以我们需要使用手动连接。
这是我使用嵌套的尝试:
var customerCategories = from c in context.Customers
join o in context.Orders on c.CustomerId equals o.CustomerId into orders
select new
{
CustomerName = c.Name,
Categories = (from o in orders
join p in context.Products on o.ProductId equals p.ProductId
join cat in context.Category on p.CategoryId equals cat.CategoryId
select cat)
};
是否有不同的(可能更好的方法)来实现相同的结果?
替代方案:多个左(组)连接
var customerCategories = from customer in context.Customers
join o in context.Orders on customer.CustomerId equals o.CustomerId into orders
from order in orders.DefaultIfEmpty()
join p in context.Products on order.ProductId equals p.ProductId into products
from product in products.DefaultIfEmpty()
join cat in context.Categories on product.CategoryId equals cat.CategoryId into categories
select new
{
CustomerName = c.Name,
Categories = categories
};