title: ASP MVC many-to-many relationship - retrieve data from associated table
body: <p>I am trying to create a database with a many-to-many relationship using EF code first.
  </p>
  
  <pre><code>public class Item
  {
      public int ItemId { get; set; }
      public String Description { get; set; }
      public ICollection&lt;Tag&gt; Tags { get; set; }
  
      public Item()
      {
          Tags = new HashSet&lt;Tag&gt;();
      }
  }
  
  public class Tag
  {
      public int TagId { get; set; }
      public String Text { get; set; }
      public ICollection&lt;Item&gt; Presentations { get; set; }
  
      public Tag()
      {
          Presentations = new HashSet&lt;Item&gt;();
      }
  }
  
  public class ItemsEntities : DbContext
  {
      public DbSet&lt;Item&gt; Items { get; set; }
      public DbSet&lt;Tag&gt; Tags { get; set; }
  }
  </code></pre>
  
  <p>After that I'm adding an Item to the database
  </p>
  
  <pre><code>var tag = new Tag { Text = "tag1" };
  var item = new Item
  {
      Description = "description1",
      Tags = new List&lt;Tag&gt;()
  };
  item.Tags.Add(tag);
  using (var db = new ItemsEntities())
  {
      db.Items.Add(item);
      db.SaveChanges();
  }
  </code></pre>
  
  <p>The problem is that I can't output items with their associated tags. The controller looks like this:
  </p>
  
  <pre><code>public ActionResult Index()
  {
      ItemsEntities db = new ItemsEntities();
      return View(db.Items.ToList());
  }
  </code></pre>
  
  <p>and the view page has the following code:</p>
  
  <pre class="lang-cs prettyprint-override"><code>@foreach (var item in Model) 
  {
     &lt;tr&gt;
      &lt;td&gt;
          @Html.DisplayFor(model =&gt; item.Description)
      &lt;/td&gt;
      &lt;td&gt;
          @foreach (var tag in item.Tags)
          {
              @tag.Text
          }
      &lt;/td&gt;
  &lt;/tr&gt;
  }
  </code></pre>
  
  <p>I expect the table to contain "description1" and "tag1" but I get only "description1". I really don't understand where the problem is. What is the correct way to do this?</p>