簡體   English   中英

通過Linq-to-SQL獲取記錄的總和和ID,並在視圖上顯示

[英]Get Sum and Id of record through Linq-to-SQL and display on view

我需要先在MVC代碼中將此SQL語句轉換為linqsql

SELECT SUM(OrderUnits), ProductID
FROM OrderProducts AS op
jOIN Orders AS o ON o.ID = op.OrderID
WHERE o.OrderStatus = 1
GROUP BY op.ProductID;

我試圖無濟於事。 我的控制器調用MostSoldItems有方法,我需要獲取此結果並將其顯示在我的視圖中。

這是我嘗試的:

var query =
    (from p in dbcontext.OrderProducts
    let totalQuantity = 
        (from op in dbcontext.Products
         join o in dbcontext.Orders on p.OrderID equals o.ID
         where o.OrderStatus == true
         select p.OrderUnits).Sum()
     orderby totalQuantity descending
     select p);

我什么都沒有。 而且我不知道如何在視圖上顯示它。

因此,我似乎想出了一個可能甚至可以解決的方法。 感謝@candide的回答,我開始研究了一段時間,並且已經弄清楚了! 下面的代碼可以很好地解決我的問題。 也感謝@Moho的貢獻。

var query = from p in dbcontext.OrderProducts
                    join pd in dbcontext.Orders on p.OrderID equals pd.ID
                    group p by p.ProductID into pdg
                    select new MostSoldModel
                    {
                        ID = pdg.Key,
                        Total = pdg.Sum(x => x.OrderUnits)
                    };

如果要查找通過相關Order.OrderStatus == true過濾並按產品分組的OrderProduct.OrderUnits的總和:

dbContext.OrderProducts
    .Where( op => op.Order.OrderStatus )
    .GroupBy( op => op.Product )
    .Select( g => new
    {
        Product = g.Key,
        TotalQuantity = g.Sum( op => op.OrderUnits ),
    } );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM