title: EF6: Collection was modified, enumeration operation may not execute
body: <p>I have been trying to add multiple objects to a DbSet, but everything I try results in a 'System.InvalidOperationException: Collection was modified; enumeration operation may not execute.' Stacktrace:</p>
  
  <blockquote>
    <p>at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
       at System.Collections.Generic.List<code>1.Enumerator.MoveNextRare()
       at System.Collections.Generic.List</code>1.Enumerator.MoveNext()
       at System.Data.Entity.Core.Objects.EntityEntry.TakeSnapshotOfRelationships()
       at System.Data.Entity.Core.Objects.Internal.EntityWrapperWithoutRelationships<code>1.TakeSnapshotOfRelationships(EntityEntry entry)
       at System.Data.Entity.Core.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName)
       at System.Data.Entity.Core.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
       at System.Data.Entity.Internal.Linq.InternalSet</code>1.&lt;>c__DisplayClassd.b__c()
       at System.Data.Entity.Internal.Linq.InternalSet<code>1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
       at System.Data.Entity.Internal.Linq.InternalSet</code>1.Add(Object entity)
       at System.Data.Entity.DbSet`1.Add(TEntity entity)</p>
  </blockquote>
  
  <p>This only occurs the second time a 'Mail' object is being added to the context The code:</p>
  
  <pre><code>            foreach (var folderId in folderIds)
              {
                  db.Mails.Add(new Mail
                  {
                      From = from,
                      To = to,
                      CC = cc,
                      Attachments = attachments,
                      BodyHtml = bodyHtml,
                      BodyPlain = bodyPlain,
                      Subject = subject,
                      Incoming = true,
                      Priority = receivedMail.Priority,
                      ReceivedOn = DateTime.UtcNow,
                      Status = MailStatus.Open,
                      Read = false,
                      Folder = db.Folders.Find(folderId)
                  });
              }
  </code></pre>
  
  <p>The only enumeration I am doing is on folderIds which is a array of ints which as you can see in the stack trace isn't the cause. I've been stuck on this for a while and tried all kinds of approaches like a temp collection and using AddRange or saving the context after every add. </p>
  
  <p>Any help with where the problem lies will be much appreciated.</p>