I'm using Entity framework core 3.1 to connect to the database, what I'm trying is to get the Highest and lowest product details which grouped by its category id. based on answers shown on this question and this question I tried to write the following code:
using Linq :
//NOTE: 'Products' is an IQueryable for all the products in the database.
var highPrice = from a in Products
group a by a.CategoryId
into prods
select prods.OrderByDescending(a => a.Price).First();
using Lambda:
//NOTE: 'Products' is an IQueryable for all the products in the database.
var highPrice = Products.GroupBy(a => a.CategoryId, (key, a) => a.OrderByDescending(a => a.Price).First()).ToList();
Both works fine only if I converted the IQueryble
of Products
to IEnumerable
using for example .ToList()
, but when running without converting it pops the following exception:
System.InvalidOperationException
HResult=0x80131509
Message=The LINQ expression '(GroupByShaperExpression:
KeySelector: (a.CategoryId),
ElementSelector:(EntityShaperExpression:
EntityType: Product
ValueBufferExpression:
(ProjectionBindingExpression: EmptyProjectionMember)
IsNullable: False))
.OrderByDescending(a => a.Price)' 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 either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().
Is there any way to get the first/Last records of IQueryable collection without converting to IEnumerable ??