LinQ sum group by使用Lambda

时间:2017-02-17 21:35:47

标签: linq entity-framework-6

帮我转换为lambda

select 
    Orders.Order_Date as date, sum(Amount) as amount
from 
    Orders 
inner join 
    OrderDetails on Orders.Order_ID = OrderDetails.Order_ID
where 
    Order_Date<= '2017-02-10' and Order_Date<= '2017-02-11'
group by 
    (Order_Date)
order by 
    date asc

我的模特:

public class TotalIncome
{
    [DataType(DataType.Date)]
    public DateTime fromDate { get; set; }
    [DataType(DataType.Date)]
    public DateTime toDate { get; set; }
    public List<IncomeByDate> ListIncome { get; set; }
}

我的控制器:

var ba = db.Orders.Include(o => o.OrderDetails)
.Where(o => o.Order_Date >= startDate)
.Where(o => o.Order_Date <= endDate);

我无法总结金额和分组。帮我解决一下

1 个答案:

答案 0 :(得分:1)

假设金额是OrderDetails的成员

var ba = db.Orders
  .Include(o => o.OrderDetails)
  .Where(o => o.Order_Date >= startDate)
  .Where(o => o.Order_Date <= endDate)
  .GroupBy(o => o.Order_Date)
  .Select(s => new {
    date = s.Key,
    amount = s.Sum(o => o.OrderDetails.Sum(od => od.Amount)),
  });