使用EntityFramework Core,我想说我有三个表:
Stores
------
StoreId int,
StoreType int,
StoreName varchar(max)
Orders
------
OrderId int,
StoreId int,
TotalCost int,
PaymentType int
OrderItem
---------
ItemId int,
OrderId int,
ItemCost int
让我们说我想要输出以下列:
StoreName
SumOfTotalWhere(OrderType==1)
SumOfTotalWhere(OrderType==2)
SumOfAllOrders
TotalNumOfOrdersForStore
NumberOfAllOrders
有没有办法在没有大量往返的情况下使用EntityFramework Sum / Group机制来实现此输出?我一直无法弄清楚语法。
答案 0 :(得分:0)
var answer = (from store in db.stores
join order in db.orders on store.StoreId equals order.StoreId into subs
from sub in subs.DefaultIfEmpty()
group sub by new {store.StoreId, store.StoreName } into gr
select new
{
StoreName = gr.Key.StoreName
SumOfTotalWhere1 = gr.Where(x => x != null && x.PaymentType == 1).Select(x => x.TotalCost).DefaultIfEmpty().Sum()
SumOfTotalWhere2 = gr.Where(x => x != null && x.PaymentType == 2).Select(x => x.TotalCost).DefaultIfEmpty().Sum()
SumOfAllOrders = gr.Where(x => x != null).Select(x => x.TotalCost).DefaultIfEmpty().Sum(),
TotalNumOfOrdersForStore = gr.Count(x => x != null)
NumberOfAllOrders = db.orders.Count()
}).ToList();