鉴于以下表格结构,如何使用实体frawework返回以下聚合的和分组字段。
必填字段
分组:
User.Forename
User.Surname
汇总:
最大(Order.OrderDate)
计数(Order.OrderId)
总和(Payment.Amount)
计数(最近60天所有订单的Order.OrderId)
总和(Payment.Amount所有订单在过去60天内)
表格
用户:
UserId(PK)
用名字
姓氏
订单:
OrderId(PK)
UserId(FK)
OrderDate
付款:
PaymentId(PK)
OrderId(FK)
PaymentAmount
答案 0 :(得分:3)
DateTime last60Days = new DateTime(xxx,xxx,xxx);
var query = from u in context.Users
group u by new
{
u.Forename,
u.Surname
} into ug
select new
{
Forename = ug.Key.Forename,
Surname = ug.Key.Surname,
MaxOrderdate = ug.SelectMany(x => x.Orders).Max(x => x.OrderDate),
OrderCount = ug.SelectMany(x => x.Orders).Count(),
Payment = ug.SelectMany(x => x.Orders.SelectMany(y => y.Payments)).Sum(x => x.PaymentAmount),
OrderCountLast60 = ug.SelectMany(x => x.Orders).Where(x => x.OrderDate > last60Days).Count(),
PaymentLast60 = ug.SelectMany(x => x.Orders.Where(x => x.OrderDate > last60Days).SelectMany(y => y.Payments)).Sum(x => x.PaymentAmount)
};