使用实体框架查询方法按查询分组

时间:2016-10-24 18:32:20

标签: c# entity-framework linq group-by include

我有这个查询,我想更改为linq查询方法:

select o.OrderID,o.OrderNo, o.OrderDate, SUM(TotalAmount) Total
 from orders o inner join
 OrderDetails e on o.OrderID=e.OrderID
 group by  o.OrderNo, o.OrderDate,o.OrderID order by o.OrderNo desc

我一直在尝试以下内容:

public List<Orders>List()
{
    var list = new List<Orders>();
    try
    {
        using (var db = new MyDatabaseEntities())
        {

            list = db.Orders.Select(o => new { o.OrderID, o.OrderNo, o.OrderDate, o.OrderDetails.TotalAmount}).
                GroupBy(x => new { x.OrderID, x.OrderNo, x.OrderDate }).
                Select(o => new
                {
                    o.Key,
                    id = o.OrderID,
                    order = o.NumOrder,
                    date = o.OrderDate,
                    Total = o.Sum(o.TotalAmount)
                }).Tolist();
        }
    }
    catch(Exception e)
    {
        throw new Exception(e.Message);
    }
    return list;
}

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我想尝试一下:

var list=db.Orders.Join(OrderDetails,
                o=>o.OrderID
                e=>e.OrderID
                (o,e)=>new{Orders=o,OrderDetails=e})
                .GroupBy(o=>new {o.OrderNo, o.OrderDate,o.OrderID})
                .OrderBy(x=>x.Key.OrderNo)
                .Select(o=>new{
                           o.Key.OrderID,
                           o.Key.OrderNo, 
                           o.Key.OrderDate, 
                           Total=o.SUM(x=>x.TotalAmount)})
                .ToList();

答案 1 :(得分:0)

试试这个: 像语法一样的SQL

from t in TblOrders
join d in TblOrderDetails
on t.Id equals d.OrderId
group d by new {t.Id, t.OrderNo, t.OrderDate} into g
orderby g.Key.OrderNo descending
select  new 
{
ID = g.Key.Id, 
OrderNo = g.Key.OrderNo,
OrderDate = g.Key.OrderDate,
amount = g.Sum(x=>x.Rate)
}

lambda喜欢:

TblOrders
   .Join (
      TblOrderDetails, 
      t => t.Id, 
      d => d.OrderId, 
      (t, d) => 
         new  
         {
            t = t, 
            d = d
         }
   )
   .GroupBy (
      temp0 => 
         new  
         {
            Id = temp0.t.Id, 
            OrderNo = temp0.t.OrderNo, 
            OrderDate = temp0.t.OrderDate
         }, 
      temp0 => temp0.d
   )
   .OrderByDescending (g => g.Key.OrderNo)
   .Select (
      g => 
         new  
         {
            ID = g.Key.Id, 
            OrderNo = g.Key.OrderNo, 
            OrderDate = g.Key.OrderDate, 
            amount = g.Sum (x => x.Rate)
         }
   )