实体框架查询

时间:2010-12-01 11:42:53

标签: c# entity-framework-4

我有桌子:顾客,订单,产品

客户有很多订单,每个订单都有很多产品。

如何编写查询以获取客户的所有产品? 我需要将它用作数据源,感谢您的帮助 再见

2 个答案:

答案 0 :(得分:2)

这应该有效:

var result = customer
                .SelectMany(x=>x.Orders)
                .Select(x=>x.Products)

您还可以添加.Distinct()以仅检索不同的产品

另一种方式是从产品:

var result = dbContext.Products
                .Where(x=>x.Orders.Any(o=>o.Customer.Id == customer.Id))

难以阅读且难以理解,但仍然有效)

答案 1 :(得分:2)

var products = from customer in customers
               from order in customer.Orders
               from product in order.Products
               select product;

只需使用LINQ SelectMany。