在实体框架中使用Join,Group By和Sum

时间:2014-01-27 17:38:56

标签: c# sql entity-framework

我的模特看起来像:

public class ReturnItem
{
    public int returnItemId { get ; set; }
    public int returnRequestId { get; set; }
    public int quantity { get; set; }
    public string item { get; set; }
}

public class ReturnRequest
{
    public int returnRequestId { get; set; }
    public string orderNumber  { get; set; }
    public IEnumerable<ReturnItem> returnItems { get; set; }
}

我有以下问题:

SELECT item, sum(quantity)
FROM ReturnItem
JOIN ReturnRequest
ON ReturnRequest.returnRequestId = ReturnItem.returnRequestId
WHERE ReturnRequest.orderNumber = '1XX'
GROUP BY item

如何将查询转换为Entity Framework并返回List<ReturnItem>?我可以使用.Include代替.Join吗?

1 个答案:

答案 0 :(得分:7)

from ri in db.ReturnItems
join rr in db.ReturnRequests
   on ri.returnRequestId equals rr.returnRequestId
where rr.orderNumber == "1XX"
group ri by ri.item into g
select new {
   Item = g.Key,
   Quantity = g.Sum(i => i.quantity)
}

您无法使用Include代替Join,因为Include已翻译为左外连接,但您需要内部加入这里。

但您可以使用navigation属性隐式执行连接:

db.ReturnRequests
  .Where(rr => rr.orderNumber == "1XX")
  .SelectMany(rr => rr.returnItems)
  .GroupBy(ri => ri.item)
  .Select(g => new {
      Item = g.Key,
      Quantity = g.Sum(ri => ri.quantity)
  });