I have a Linq expression that (for northwind) gets the total qty ordered per product for customer id ‘ALFKI’
from od in db.OrderDetails
where od.Order.CustomerID == "ALFKI"
group od by od.Product.ProductName into g1
select new { ProductName = g1.Key, Total = g1.Sum(od => od.Quantity) }
This is fine but to fully understand Linq, I want to try and formulate the expression in a world where Linq2Sql doesn’t nicely build the property bridges through foreign keys.
For instance, in the above expression, I’m accessing od.Order.CustomerID. I want to assume that od.OrderID is as far as I can go.
Looking at the SQL for the expression, I have:
SELECT SUM(CONVERT(Int,[t0].[Quantity])) AS [Total], [t2].[ProductName]
FROM [Order Details] AS [t0]
INNER JOIN [Orders] AS [t1] ON [t1].[OrderID] = [t0].[OrderID]
INNER JOIN [Products] AS [t2] ON [t2].[ProductID] = [t0].[ProductID]
WHERE [t1].[CustomerID] = @p0
GROUP BY [t2].[ProductName]
This is as far as I’ve managed to get:
from od in db.OrderDetails
join o in db.Orders on od.OrderID equals o.OrderID
join p in db.Products on od.ProductID equals p.ProductID
where o.CustomerID == "ALFKI"
group od by od.ProductID into g1
select new { ProductName = g1.Key, Total = g1.Sum(od => od.Quantity) }
This is almost there but g1.Key is referring to the ProductID. I can’t seem to get at the ProductName and the order quantity at the same time.
Thanks
Try creating a new anonymous type for your group by: