基于另一个Linq对象创建Linq对象

时间:2014-03-26 14:59:59

标签: c# linq linq-to-sql

我在Linqpad中使用Linq to SQL来获取一些数据。

我需要使用3个表来执行以下步骤:

1)通过邮政编码(客户表)

选择客户

2)获取这些客户的所有交易ID(交易表)

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

所以我开始很容易并抓住客户:

string pc = "123";

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

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

我为这样一个基本问题道歉,但我刚开始使用Linq。

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

1 个答案:

答案 0 :(得分: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