I’ve been struggling with LINQ a bit, and was after help. I could do it in SQL, but can’t seem to work out how to in LINQ.
I have a SQL Compact 4.0 Database, with a Entity Framework 4.0 EDMX modelling it, in C#.
This is the scenario, these tables:
Customers – OrderDetails – Orders
The OrderDetails table is a non-payload table, just facilitating the many to many join.
If I’m given an CustomerId Number as a parameter, I want to return an IEnumerable<Orders>.
In SQL I would’ve written this as:
SELECT Orders.*
FROM OrderDetails INNER JOIN
Orders ON OrderDetails.OrderId = Orders.OrderId INNER JOIN
Customers ON OrderDetails.CustomerId = Customers.CustomerId
How can I do this in LINQ?
If you want to “think in SQL”, you can do this as a query expression like this:
Note that this doesn’t actually touch the Customers table at all… I’m assuming that there are enough relational constraints to ensure that
OrderDetails.CustomerIdreally does refer to a real customer.If you have all the relationships set up appropriately, however, you can use something like Sjoerd’s answer. Note that that will first fetch the
Customerentity, whereas the above query doesn’t. It’s a more OO way of thinking about things though.EDIT: As it appears your relationships are set up appropriately, two options: