I am trying to create query using LINQ to Entities that calculates an average of a rating for a product. I project the average for each product to an anonymous object, before ordering the ratings. I then want to take only a portion of the results.
The query is below:
var query = Items.GroupBy(review => review.Product)
.Select(group => new
{
Product = group.Key,
Rating = group.Average(review => review.Rating)
})
.OrderByDescending(pr => pr.Rating)
.Skip(itemsToSkip)
.Take(count)
.ToList();
The query that is generated looks like the following:
{SELECT
1 AS [C1],
[GroupBy1].[K1] AS [ProductId],
[GroupBy1].[K2] AS [TotalImages],
[GroupBy1].[K3] AS [TotalVideos],
[GroupBy1].[K4] AS [TotalAudioRecordings],
[GroupBy1].[K5] AS [Name],
[GroupBy1].[K6] AS [DiscountedPrice],
[GroupBy1].[K7] AS [Status],
[GroupBy1].[A1] AS [C2]
FROM ( SELECT
[Extent2].[ProductId] AS [K1],
[Extent2].[TotalImages] AS [K2],
[Extent2].[TotalVideos] AS [K3],
[Extent2].[TotalAudioRecordings] AS [K4],
[Extent2].[Name] AS [K5],
[Extent2].[DiscountedPrice] AS [K6],
[Extent2].[Status] AS [K7],
AVG([Extent1].[Rating]) AS [A1]
FROM [dbo].[ProductReviews] AS [Extent1]
LEFT OUTER JOIN [dbo].[Products] AS [Extent2] ON [Extent1].[Product_ProductId] = [Extent2].[ProductId]
GROUP BY [Extent2].[ProductId], [Extent2].[TotalImages], [Extent2].[TotalVideos], [Extent2].[TotalAudioRecordings], [Extent2].[Name], [Extent2].[DiscountedPrice], [Extent2].[Status]
) AS [GroupBy1]}
The query doesn't work to skip any items, or to take only a few results. Rather it returns a calculation of the average for every product in the database.
Is it possible to utilise Skip and Take, as I am attempting to do? If so, how do I correct the query to get the desired result? It is desirable that I do not pull back all the data from the database.
I think you may need to add one more select to your query:
var query = Items.GroupBy(review => review.Product)
.Select(group => new
{
Product = group.Key,
Rating = group.Average(review => review.Rating)
})
.OrderByDescending(pr => pr.Rating)
.Select(x => new { Product = x.Product, Rating = x.Rating })
.Skip(itemsToSkip)
.Take(count)
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With