EF6:集合已修改,枚举操作可能无法执行

EF6: Collection was modified, enumeration operation may not execute

我一直在尝试将多个对象添加到 DbSet,但我尝试的所有操作都会导致 'System.InvalidOperationException: Collection was modified; enumeration operation may not execute.' Stacktrace:

at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) at System.Collections.Generic.List1.Enumerator.MoveNextRare() at System.Collections.Generic.List1.Enumerator.MoveNext() at System.Data.Entity.Core.Objects.EntityEntry.TakeSnapshotOfRelationships() at System.Data.Entity.Core.Objects.Internal.EntityWrapperWithoutRelationships1.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.InternalSet1.<>c__DisplayClassd.b__c() at System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity) at System.Data.Entity.DbSet`1.Add(TEntity entity)

这只会在第二次将 'Mail' 对象添加到上下文时发生代码:

            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)
                });
            }

我正在做的唯一枚举是在 folderIds 上,它是一个整数数组,正如您在堆栈跟踪中看到的那样,这不是原因。我已经坚持了一段时间并尝试了各种方法,例如临时集合和使用 AddRange 或在每次添加后保存上下文。

对于问题所在的任何帮助将不胜感激。

还有附件collection?如果它来自任何数据库 object 尝试在分配时调用 ToList()。

 foreach (var folderId in folderIds)
        {
            db.Mails.Add(new Mail
            {
                From = from,
                To = to,
                CC = cc,
                Attachments = attachments.ToList(),
                BodyHtml = bodyHtml,
                BodyPlain = bodyPlain,
                Subject = subject,
                Incoming = true,
                Priority = receivedMail.Priority,
                ReceivedOn = DateTime.UtcNow,
                Status = MailStatus.Open,
                Read = false,
                Folder = db.Folders.Find(folderId)
            });
        }