2016-07-08 62 views
-2

我遇到了編碼我的linq查詢的問題。將SQL查詢更改爲linq查詢 - 語法

這是我的SQL查詢:

select 
    price, (cast(sum(Quantity) as decimal(7,2))) 
from 
    OrderDetails 
where 
    ItemID = 1000 
group by 
    price 
order by 
    price 

這是我的LINQ查詢:

var result = from od in db.OrderDetails 
      where od.ItemID == 1000 
      orderby od.Price 
      group by price 
      select od.price, (cast(sum(od.Quantity) as decimal(7, 2))); 

這LINQ查詢似乎是不正確的。什麼是正確的語法?

回答

1

這應該工作: (你需要移動的順序部分是分組後)

var q = (from o in context.OrderDetails 
      where o.ItemID == 1000 
      group o by o.price into grp 
      select new 
      { 
       Price = grp.Key, 
       Quantity = grp.Sum(x => x.Quantity) 
      }).OrderBy(a => a.Price); 
+1

它不工作。 – coco

+1

它的工作原理。謝謝!!! – coco