Fadi
Fadi

Reputation: 2370

how to get the average star rating using entity framework .average() method

I'm new in mvc and entity framework and I develop a star rating system for products. I'm trying to get the average star rating of a product and I built my database like this:

User table : UserID PK , UserName , StarRatingDetails FK

Product Table : ProdactID PK, ProudactName , StarRatingDetails FK

StarRatingDetails : ProdactID PK1 , UserID PK2 , VoteValue

so I'm trying to get the average star rate using the entity framework .average() method like this:

   var products = db.Products.Include(p => p.StarRatingDetail).ToList();
   var voteCounts = db.StarRatingDetail.ToList();

         foreach (var av in voteCounts)
        {
            var avarage = new { starAvarage = Convert.ToInt32(voteCounts.Average(avv => avv.VoteValue)) };

        }

It works and gets every average star rate of a product, but how can I associate the average rate with the correct product and send it to the view? If there's any other way I will be very thankful for any help.

Upvotes: 0

Views: 1906

Answers (1)

James
James

Reputation: 82096

Assuming Product has a 1..* relationship with StartRatingDetail

var productWithVotes = db.Products.Include(p => p.StarRatingDetail)
                                  .Select(x => new {
                                      Product = x,
                                      VoteAverage = x.StarRatingDetail.Average(r => r.VoteValue)     
                                  });

Note - Average will throw an exception if the collection is empty therefore you might need a check before you call it

VoteAverage = x.StarRatingDetail.Any() ? 
    x.StarRatingDetail.Average(v => v.VoteValue) : 0

Live example

Upvotes: 1

Related Questions