I'm running into an issue in the View with pulling data from different entities. Basically I have a bridging entity CategoryProduct that brings together Category and Product data together. What I want to ultimately display is a list of products and for each of those products - their categories. However I'm completely stuck on how to make that last part - display categories - happen.
Here's the code for my model -
public class Product
{
public int ProductId { get; set; }
public string Title { get; set; }
public virtual ICollection<CategoryProduct> CategoryProducts { get; set; }
}
public class CategoryProduct
{
public int CategoryProductID { get; set; }
public int CategoryId { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Title { get; set; }
public virtual ICollection<CategoryProduct> CategoryProducts { get; set; }
}
My Controller is pretty simple, it's just pushing that bridging entity to the View:
public ActionResult Index()
{
return View(db.CategoryProducts.ToList());
}
Finally my view displays Products and Categories but right now it's just creating extra rows for the same product if it has a different category, e.g. Product 1: Category 1, Product 1: Category 2 and so on. And Where I want to get to is Product 1: Category 1, Category 2.
@model IEnumerable<ProductsCode.Models.CategoryProduct>
<h2>Index</h2>
<table>
<tr>
<th>Title</th>
<th>Category</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Product.Title)
</td>
<td>
@foreach (var categories in item)
{
@Html.DisplayFor(modelItem => item.Why.Title)
}
</td>
</tr>
}
</table>
Errors out on: Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'ProductsCode.Models.CategoryProduct' because 'ProductsCode.Models.CategoryProduct' does not contain a public definition for 'GetEnumerator'
EDIT: added the other foreach loop and the error.