2013-01-22 216 views
-2

我想查詢一個對象的層次結構是這樣的:C#lambda表達式,子子查詢

客戶 - >IList訂單 & 訂單 - >IList產品

Customer對象擁有一組訂單,我的Order對象有一個產品集合。

我想要做的是讓訂購特定產品的客戶。我會通過product id來查詢。在查詢結束時,我想獲得Customer list

我試過了,但沒有奏效。

public ICollection<Customer> GetByParticularProduct(int productId) 
{ 

    return allCustomers 
    .Where(customer => customer.Orders 
.Any(order => order.Products 
.Any(prod => prod.Id == productId))) 
    .ToList(); 
} 

我該如何解決這個問題?

+1

你所說的 「沒有工作」 的意思是?什麼是'ProductsAny()'? – millimoose

+0

對不起,我修改了它。我的意思是沒有工作。我得到一個ArgumentNullException,並發現問題不是我的查詢。這是我的映射。我的訂單集合沒有被映射到正確的位置,而且它是空白的。現在我將其映射到正確的位置並且它可以正常工無論如何感謝您的關注... – ayk

回答

-1
return allCustomers 
    .Where(customer => customer.Orders 
     .Any(order => order.Products 
      .Any(prod => prod.Id == productId))).ToList(); 

return allCustomers 
    .Where(customer => customer.Orders 
     .Any(order => order.ProductId == productId))).ToList(); 
+0

您的第一張照片看起來與OP提供的樣本完全相同 – Chad

0

如果您的收藏可以包含null的,你可以試試這個

public ICollection<Customer> GetByParticularProduct(int productId) 
{ 
    return (from cust in allCustomers.Where(x => x != null) 
      let orders = cust.Orders.Where(x => x != null) 
      let prods = orders.SelectMany(x => x.Products).Where(x => x != null) 
      where prods.Any(x => x.Id == productId) 
      select cust) 
      .ToList(); 
}