If you're using Entity Framework, then you need to use the
Include
method:
Entity Framework Loading Related Entities[
^]
Product product = repository.Products
.Include(p => p.Reviews)
.FirstOrDefault(p => p.ProductID == productId);
If you're using something else, then you need to tell us what you're using, and show us the relevant parts of the code.
EDIT:
First, update your repository to return
IQueryable<...>
instead of
IEnumerable<...>
:
public interface IProductsRepository
{
IQueryable<Product> Products { get; }
IQueryable<Review> Reviews { get; }
...
}
public class EFProductRepository : IProductsRepository
{
...
public IQueryable<Product> Products
{
get { return context.Products; }
}
public IQueryable<Review> Reviews
{
get { return context.Reviews; }
}
...
}
Then, add the navigation properties to define the relationship between the
Product
and
Review
classes:
public class Product
{
...
public virtual ICollection<Review> Reviews { get; set; }
}
public class Review
{
...
[Required]
public int ProductID { get; set; }
public virtual Product Product { get; set; }
...
}
Make sure you have a
using System.Data.Entity;
statement at the top of your controller file.
Now you can use the
Include
method to eagerly load the reviews for the product:
Product product = repository.Products
.Include(p => p.Reviews)
.FirstOrDefault(p => p.ProductID == productId);
And you can display your reviews in your view:
@HTML.DisplayFor(model => model.ProductName)
<p>Reviews:</p>
<ul>
@foreach (var review in model.Reviews)
{
<li>@HTML.Partial("_Review", review)</li>
}
</ul>