0

我有一个 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 和订单数量。

谢谢

4

2 回答 2

3

尝试通过以下方式为您的组创建一个新的匿名类型:

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 new { p.ProductID, p.ProductName } into g1
select new { 
    ProductName = g1.Key.ProductName, 
    Total = g1.Sum(od => od.Quantity) }
于 2012-06-30T17:09:10.527 回答
0

除了凯文的回答,使用复合键,我还设法以另一种方式做到这一点:

from item in (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"
                  select new {ProductName = p.ProductName, Quantity = od.Quantity }
              )
              group item by item.ProductName into g1
              select new {ProductName = g1.Key, Total = g1.Sum(od=>od.Quantity) }

更一般地说,如果您想将所有连接拼接在一起并引用任何字段:

from item in (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"
                 select new { p, od }
             )
             group item by item.p.ProductName into g1
             select new { ProductName = g1.Key, Total = g1.Sum(all => all.od.Quantity)}
于 2012-06-30T17:44:41.550 回答