title: EF, AddRange, Collection was modified; enumeration operation may not execute
body: <p>Problem: I'm trying to save a list of objects into the database, using the AddRange.</p>
  
  <p>The Setup: I have a database of two tables:</p>
  
  <pre><code>BookTitles:
  - Book_Id
  - BookName
  
  BookAuthors:
  - Author_Id
  - AuthorName
  - Book_Id
  </code></pre>
  
  <p>In the BookAuthors table, the "Book_Id" is the Foreign Key from BookTitles table.
  I Use Entity Framework, Database First. EF created the models for me, so the model of BookTitles looks like this:</p>
  
  <pre><code>public partial class BookTitles
  {
      public BookTitles()
      { this.BookAuthors = new HashSet&lt;BookAuthors&gt;(); }
  
      public int Book_Id { get; set; }
      public string BookName { get; set; }
  
      public virtual ICollection&lt;BookAuthors&gt; BookAuthors { get; set; }
  }
  </code></pre>
  
  <p>THE WAY IT WORKS: If i use this function to add one Book record (which will contain a list of BookAuthors) to the database, it works fine. And the Function below will add one record to the BookTitles table, and thwo record to the BookAuthors table. Here I use the "Add" method:</p>
  
  <pre><code>private static void InsertBook()
  {
      using (var db = new BooksContext())
      {
          var authors = new List&lt;BookAuthors&gt;()
          {
              new BookAuthors() {AuthorName = "Author 1"},
              new BookAuthors() {AuthorName = "Author 2"}
          };
  
          var book = new BookTitles {BookName = "Book1", BookAuthors = authors};
  
          db.BookTitles.Add(book);
          db.SaveChanges();
       }
   }
  </code></pre>
  
  <p>THE WAY IT DOESN'T WORK: If i try to add a list of Books to the database, using the AddRange(), it will throw an error "Collection was modified; enumeration operation may not execute":</p>
  
  <pre><code>private static void AddRangeOfBooks()
  {
      using (var db = new BooksContext())
      {
          var listOfAuthors = new List&lt;BookAuthors&gt;
          {
              new BookAuthors() {AuthorName = "Author1"},
              new BookAuthors() {AuthorName = "Author2"}
          };
  
          var listOfBooks = new List&lt;BookTitles&gt;
          {
              new BookTitles() {BookName = "Book 1", BookAuthors = listOfAuthors},
              new BookTitles() {BookName = "Book 2", BookAuthors = listOfAuthors}
          };
  
          db.BookTitles.AddRange(listOfBooks);
          db.SaveChanges();
      }
  }
  </code></pre>
  
  <p>Why it throws the error? Why does it work with Add() method (adding a single record) and doesn't work with AddRange() (adding a range of records)?</p>