簡體   English   中英

選擇一個表並使用實體框架在另一表中求和

[英]select one table and sum row in another table with entity framework

我有兩個表是產品和訂單,我要選擇所有產品,並以計數的產品。 例:

Product
ID   |   Name   | ....
P001  ProductA    ....
P002  ProductB    ....
P003  ProductC    ....
P004  ProductD    ....

Order
ID   | CustomerID | ...
O001   C001
O002   C002

OrderDetails
ID   | OrderID | ProductID | Quantity | ....
1      O001      P001        2          ....
2      O001      P002        1          ....
3      O002      P002        4          ....
4      O002      P004        1          ....

Result is:
ID   |   Name   | Count | ....
P001  ProductA    2       ....
P002  ProductB    5       ....
P003  ProductC    0       ....
P004  ProductD    1       ....

我在下面嘗試代碼但是錯了

db.tblProducts
  .Join(db.tblOrderDetails, p => p.ProductID, o => o.ProductID, (p, o) => new { Product = p, OrderDetails = o })
  .Select(x => new { x.Product , x.OrderDetails  })
  .ToList();

解析數據以查看{ Product = MvcWebProject.Entities.tblProduct, OrderDetails = MvcWebProject.Entities.tblOrderDetails } ,但是我無法選擇值。

foreach (var item in ViewBag.products)
{
    <p>@item.Product</p> //'object' does not contain a definition for 'Product'
}

未經測試,希望這可以幫助您入門:

from product in db.tblProducts
let summedCount=(from orderDetail in product.OrderDetails
                 select orderDetail.Quantity).Sum()
select new {Id=product.Id,Name=product.Name,Count=summedCount}

我創建包含tblProduct的新模型並計數

public class Product
{
    public Product()
    {
        Prod = new tblProduct();
    }
    public tblProduct Prod { get; set; }
    public Nullable<int> Count { get; set; }
}

控制器中的代碼

var products = db.tblProducts
                     .Select(x => new Product { 
                             Prod = x, 
                             Count = db.tblOrderDetails
                                       .Where(z => z.ProductID == x.ProductID)
                                       .Sum(z => z.Quantity) })
                     .ToList();
return View(products)

並鑒於

foreach (var item in Model)
{
    <p>@item.Prod.MSP</p>
    <p>@{int? c = 0;if (item.Count == null) { c = 0; } else { c = item.Count; }}@c</p>
}

嘗試這個

select Product.ID, Product.Name, SUM(OrderDetails.Quantity) as [Count] from Product inner join
OrderDetails on Product.ID=OrderDetails.Quantity group by Product.ID;

暫無
暫無

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

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