我有一个 Linq 表达式,它(对于北风)获取客户 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) }
这很好,但要完全理解 Linq,我想尝试在 Linq2Sql 不能很好地通过外键构建属性桥的世界中制定表达式。
例如,在上面的表达式中,我访问的是 od.Order.CustomerID。我想假设 od.OrderID 是尽我所能。
查看表达式的 SQL,我有:
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]
这是我设法得到的:
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) }
这几乎就在那里,但 g1.Key 指的是 ProductID。我似乎无法同时获得 ProductName 和订单数量。
谢谢