2014-03-26 54 views
1

我在Linqpad中使用Linq to SQL来获取某些数据。基于另一个Linq对象创建Linq Obect

我有3个表,我需要用它来执行以下步骤:通过邮政编码

1)选择客户(Customer表)

2)获取所有交易编号为这些客户(交易表)

3)获取所有transaxction的ID(表逐项逐项项目)

所以我开始时很容易抢客户:

string pc = "123"; 

var cust = 
from c in Customers 
where c.PostCode.StartsWith(pc) == true 
select c; 

现在我需要创建一个新的Linq对象,该对象具有基于“CustomerID”字段的事务表查找,但我不知道如何执行此操作。我曾尝试过一些foreach循环,但无法获得正确的语法。做了一些谷歌搜索,看到帖子说不使用foreach循环与linq对象,因为你应该使用内置的Linq功能,但我找不到任何我需要的例子。

我对这样一个基本问题表示歉意,但我刚开始使用Linq。

如何使用基于CustoomerID字段的所有交易记录创建下一个Linq对象?

回答

1

您可以对联合使用单个查询。如果您有导航属性在实体:

from c in Customers 
from t in c.Transactions 
from i in t.ItemizedItems 
where c.PostCode.StartsWith(pc) 
select i 

Labda语法:

Customers.Where(c => c.PostCode.StartsWith(pc)) 
     .SelectMany(c => c.Transactions) 
     .SelectMany(t => t.ItemizedItems); 

如果没有导航属性:

from c in Customers 
join t in Transactions on c.ID equals t.CustomerID 
join i in t.ItemizedItems on t.ID equals i.TransactionID 
where c.PostCode.StartsWith(pc) 
select i  
+1

谢谢!这完全回答了我的问题:) – Guerrilla