0

(ノースウィンドの場合)顧客ID「ALFKI」の製品ごとに注文された合計数量を取得するLinq式があります

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 に答える