title: Many-to-Many Relationships in EF7 - Select query for a list including related data
body: <p>I am building a blog with the following Many-to-Many relationship on the content -> category tables. I have used the following code to generate the tables in EF7:</p>
  
  <pre><code>public class Category
  {
      public int Id { get; set; }
      public string Name { get; set; }
  
      public virtual ICollection&lt;Categorization&gt; Categorization { get; set; }
  }
  
  public class Categorization
  {
      public int ContentId { get; set; }
      public Content Content { get; set; }
  
      public int CategoryId { get; set; }
      public Category Category { get; set; }
  }
  
  public class Content
  {
      [Key]
      public int Id { get; set; }
      public string Title { get; set; }
      public string Excerpt { get; set; }
      public string Body { get; set; }
  
      ...
  
      public virtual ICollection&lt;Categorization&gt; Categorization { get; set; }
  }
  </code></pre>
  
  <p>However, when I attempt to load a list of categories, including the content associated with an EF7 query as follows, I get an error.</p>
  
  <pre><code>categories = await _db.Categories
                        .Include(c =&gt; c.Categorization)
                        .ThenInclude(c =&gt; c.Content)
                        .OrderByDescending(c =&gt; c.Categorization.Count)
                        .ToListAsync();
  </code></pre>
  
  <p>This is the error page that I get when this is called.</p>
  
  <blockquote>
    <p>A database operation failed while processing the request.</p>
    
    <p>AggregateException: One or more errors occurred.  AggregateException:
    One or more errors occurred.  AggregateException: One or more errors
    occurred.  AggregateException: One or more errors occurred. 
    SqlException: Invalid column name 'Id'.  There are pending model
    changes for ApplicationDbContext Scaffold a new migration for these
    changes and apply them to the database from the command line:</p>
  
  <pre><code>dnx ef migrations add [migration name] 
  dnx ef database update
  </code></pre>
  </blockquote>
  
  <p>Interesting note: When i remove the line</p>
  
  <pre><code> .Include(c =&gt; c.Categorization).ThenInclude(c =&gt; c.Content)
  </code></pre>
  
  <p>It will sometimes work correctly, as in load the categorization, however this does not ALWAYS happen, sometimes the categorization doesn't load and I only have null references for Categorization in each Category class in the generated enumerable.</p>