如何将此T-SQL查询转换为LINQ语法?

时间:2016-11-13 19:47:09

标签: linq tsql

我试图在LINQ中编写下面的T-SQL查询。但我无法弄清楚语法。请帮帮我。

SELECT
    MONTH( O.Date) AS Month,
    SUM( P.Price * PO.Quantity ) AS OrderSumPerMonth 
FROM
    Products P
    INNER JOIN ProductOrders PO ON P.ProductId = PO.ProductId
    INNER JOIN Orders O ON PO.OrderId = O.OrderId
GROUP BY
    MONTH( O.Date );

1 个答案:

答案 0 :(得分:1)

var query = dbContext.ProductOrders
    .GroupBy( po => new { po.Order.Date.Year, po.Order.Date.Month } )
    .Select( grp => new
    {
        grp.Key,
        OrderSumPerMonth = grp.Sum( po => po.Product.Price * po.Quantity )
    } );

foreach(var row in query) {
    WriteLine( "{0}/{1} - {2:C}", row.Key.Year, row.Key.Month, row.OrderSumPerMonth );
}