title: Seeding many-to-many databases in EFCore5 with ModelBuilder?
body: <p>There are <a href="https://stackoverflow.com/questions/6404629/seed-many-to-many-data-in-entity-framework">many</a> <a href="https://stackoverflow.com/questions/34640542/seeding-many-to-many-data">questions</a> about seeding many-to-many relationships in Entity Framework. However, most of them are extremely old, and many-to-many behavior has <a href="https://devblogs.microsoft.com/dotnet/announcing-entity-framework-core-efcore-5-0-rc1/#many-to-many" rel="noreferrer">changed significantly in EFCore5</a>. The <a href="https://docs.microsoft.com/en-us/ef/core/modeling/data-seeding" rel="noreferrer">official docs recommend</a> overriding <code>OnModelCreating</code> to implement <code>ModelBuilder.Entity&lt;&gt;.HasData()</code>.</p>
  <p>However, with the new many-to-many behavior (without explicit mappings), I can find no clear path to seed the intermediate tables. To use the example of <a href="https://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration" rel="noreferrer">this tutorial</a>, the <code>BookCategories</code> class is now implicit. Therefore, there is no path to explicitly declare the intermediate table values while seeding.</p>
  <p>I've also tried simply assigning the arrays, e.g.,:</p>
  <pre><code>public class Book
  {
      public int BookId { get; set; }
      public string Title { get; set; }
      public ICollection&lt;Category&gt; Categories { get; set; }
  }  
  public class Category
  {
      public int CategoryId { get; set; }
      public string CategoryName { get; set; }
      public ICollection&lt;Book&gt; Books { get; set; }
  }  
  </code></pre>
  <p>And then at seed time:</p>
  <pre><code>Book book = new Book() { BookId = 1, Title = &quot;Brave New World&quot; }
  
  Category category = new Category() { CategoryId = 1, CategoryName = &quot;Dystopian&quot; }
  
  category.Books = new List&lt;Book&gt;() { book };
  book.Categories = new List&lt;Category&gt;() { category };
  
  modelBuilder.Entity&lt;Book&gt;().HasData(book);
  modelBuilder.Entity&lt;Category&gt;().HasData(category);
  </code></pre>
  <p>... but there are no entries created for <code>BookCategories</code> in the resulting migration. This was somewhat expected, as <a href="https://www.learnentityframeworkcore.com/migrations/seeding" rel="noreferrer">this article suggests</a> that one must explicitly seed the intermediate table. What I want is something like this:</p>
  <pre><code>modelBuilder.Entity&lt;BookCategory&gt;().HasData(
    new BookCategory() { BookId = 1, CategoryId = 1 }
  );
  </code></pre>
  <p>However, again, since there is no concrete class to describe <code>BookCategories</code> in EFCore5, the only way I can think of to seed the table is to manually edit the migration with additional <code>MigrationBuilder.InsertData</code>  commands, which rather defeats the purpose of seeding data via application code.</p>