将SQL查询更改为linq查询 - 语法

时间:2016-07-08 08:39:14

标签: c# sql linq

我的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 个答案:

答案 0 :(得分: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);