我在使用以下 LINQ 查询时遇到问题:
var baselineDate = DateTime.Now.AddDays(-365);
var salesPerformance = _context.SalesOrder.Where(p => p.OrderDate >= baselineDate).Where(p => p.CustomerId == customerId)
.GroupBy(p => p.OrderDate.Month)
.Select(g => new CustomerSalesPerformance
{
Month = g.Key,
Sales = g.Sum(i => i.SalesOrderItems.Sum(i => i.Qty * i.UnitPrice))
});
return await salesPerformance.ToListAsync();
我的目标是生成一份包含去年每位客户销售额的报告:
一月:£13,500
二月:0.00 英镑
3 月:56,000 英镑
等
我无法在此查询中看到任何无法翻译的内容(例如 DateTime 函数)。
错误信息:
<块引用>{"LINQ 表达式 'GroupByShaperExpression:\r\nKeySelector: DATEPART(month, s.OrderDate), \r\nElementSelector:EntityShaperExpression: \r\n EntityType: SalesOrder\r\n ValueBufferExpression: \r\n ProjectionBindingExpression : EmptyProjectionMember\r\n IsNullable: False\r\n\r\n .Sum(i => i.SalesOrderItems\r\n .Sum(i => (Nullable)i.Qty * i.UnitPrice))' 可以不会被翻译。要么以可翻译的形式重写查询,要么通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用来显式切换到客户端评估。请参阅https://go.microsoft.com/fwlink/?linkid=2101038了解更多信息。"}
我的模型:
销售订单
SalesOrderId (PK, int)
CustomerId (FK, int)
订单日期(日期时间)
销售订单项
SalesOrderItemId (PK, int)
数量(整数)
单价(十进制)
SalesOrderId (FK, int)
我的 DTO 模型:
客户销售业绩
月份(整数)
销售额(十进制?)
答案 0 :(得分:1)
在 GroupBy 之后,您不能使用导航属性。因此,只需重写查询即可做到这一点。
var salesPerformance =
from so in _context.SalesOrder
where so.OrderDate >= baselineDate && so.CustomerId == customerId)
from sio in so.SalesOrderItems
group sio by so.OrderDate.Month into g
select new CustomerSalesPerformance
{
Month = g.Key,
Sales = g.Sum(i => ii.Qty * i.UnitPrice)
});