title: ASP.NET MVC3 Razor Querying inside a model (foreach within foreach)
body: <p>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.</p>
  
  <p>Here's the code for my model - </p>
  
  <pre><code>public class Product
      {   
          public int ProductId { get; set; }
          public string Title { get; set; }
          public virtual ICollection&lt;CategoryProduct&gt; 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&lt;CategoryProduct&gt; CategoryProducts { get; set; }
      }
  </code></pre>
  
  <p>My Controller is pretty simple, it's just pushing that bridging entity to the View:</p>
  
  <pre><code>public ActionResult Index()
  {
      return View(db.CategoryProducts.ToList());
  }
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>@model IEnumerable&lt;ProductsCode.Models.CategoryProduct&gt;
  &lt;h2&gt;Index&lt;/h2&gt;
  &lt;table&gt;
      &lt;tr&gt;
          &lt;th&gt;Title&lt;/th&gt;
          &lt;th&gt;Category&lt;/th&gt;
      &lt;/tr&gt;
  
  @foreach (var item in Model) {
      &lt;tr&gt;
          &lt;td&gt;
              @Html.DisplayFor(modelItem =&gt; item.Product.Title)
          &lt;/td&gt;
          &lt;td&gt;
             @foreach (var categories in item)
             {
               @Html.DisplayFor(modelItem =&gt; item.Why.Title)            
             }   
          &lt;/td&gt;
      &lt;/tr&gt;
  }
  &lt;/table&gt;
  </code></pre>
  
  <p>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'</p>
  
  <p>EDIT: added the other foreach loop and the error.</p>