Reputation: 69
I am having an issue with the following LINQ query:
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();
I am aiming to produce a report with sales per customer for the last year:
Jan: £13,500
Feb: £0.00
Mar: £56,000
etc
I am unable to see anything in this query which would not translate (such as a DateTime function).
The error message:
{"The LINQ expression '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))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."}
My models:
SalesOrder
SalesOrderId (PK, int)
CustomerId (FK, int)
OrderDate (DateTime)
SalesOrderItem
SalesOrderItemId (PK, int)
Qty (int)
UnitPrice (decimal)
SalesOrderId (FK, int)
My DTO Model:
CustomerSalesPerformance
Month (int)
Sales (decimal?)
Upvotes: 0
Views: 433
Reputation: 27406
After GroupBy, you cannot use navigation properties. So just rewrite query to do that before.
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)
});
Upvotes: 1