使用实体框架选择另一个表中的一个表和总和行

时间:2014-07-19 19:20:36

标签: c# 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'
}

3 个答案:

答案 0 :(得分:0)

未经测试,希望这能让你开始:

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}

答案 1 :(得分:0)

我创建的新模型包含tblProduct和count

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>
}

答案 2 :(得分:-1)

试试这个

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