I am using Linq to SQL in Linqpad to get to some data.

I have 3 tables I need to use to do the following steps:

1) Select customers by postcode (Customer table)

2) Get all transaction ID's for these customers (Transaction table)

3) Get itemized items for all transaxction ID's (Itemized table)

So i start out easy enough and grab the customers:

string pc = "123";

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

Now I need to create a new Linq object that has the lookup from transaction table based on the "CustomerID" field but I am not sure how to do this. Ive experimented with some foreach loops but cant get syntax right. Did some googling and saw posts saying not to use foreach loops with linq objects as you should use inbuilt Linq functionality but I couldnt find any examples doing what I needed.

I apologise for such a basic question but I have just started using Linq.

How do I create the next Linq object with all transaction records based on the CustoomerID field?

有帮助吗?

解决方案

You can use single query with joins. If you have navigation properties in your entities:

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

Labda syntax:

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

If you don't have navigation properties:

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    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top