Reputation: 9
I have an ASP.NET MVC5 application for a store. The application is already built, but I have to add some features.
The application uses an domain layer with interfaces and Entity Framework.
There is a database table Products
, and I created a table Reviews
. The tables are linked by ProductId <> ReviewId
and have a one-to-many relationship.
Products
:
Review
:
I have created a new Entity framework ReviewRepository
with a function:
getAverageForProduct(int ProductId)
which calculates the average review rating.
public double GetReviewAverage(int ProductId)
{
if (context.Review.Count(x => x.Product.ProductId == ProductId) == 0)
{
return 0;
}
else
{
return Math.Round(context.Review.Where(x => x.Product.ProductId == ProductId).Average(x => x.ReviewRating), 0);
}
}
Now I want to show the average rating on the product page.
The view is set up like this:
@model IEnumerable<Domain.Entities.Products>
The products are show with the following loop:
@foreach (var m in Model)
{
}
How can I calculate the average review rating for every product? This is because the view uses the ProductRepository
from the controller (function: getAllProducts()
), not the ReviewRepository
.
The application does not use view models.
Upvotes: 0
Views: 95
Reputation: 9
Solved the problem. Created a simple view model.
The Viewmodel:
public class PopularProductList
{
public Product Product { get; set; }
public double Average { get; set; }
}
In the controller:
var model = new List<PopularProductList>();
foreach (var p in ProductRepository.GetPopularProducts())
{
var ProductList = new PopularProductList();
ProductList.Product = p;
ProductList.Average = ReviewRepository.GetReviewAverage(p.ProductId);
model.Add(ProductList);
}
return View("Index", model);
Upvotes: 1