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

时间:2015-11-09 12:05:11

标签: c# .net entity-framework linq

我一直在尝试向DbSet添加多个对象,但是我尝试的所有内容都会导致'System.InvalidOperationException:Collection被修改;枚举操作可能无法执行。堆栈跟踪:

  

在System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource资源)      在System.Collections.Generic.List 1.Enumerator.MoveNextRare() at System.Collections.Generic.List 1.Enumerator.MoveNext()      在System.Data.Entity.Core.Objects.EntityEntry.TakeSnapshotOfRelationships()      在System.Data.Entity.Core.Objects.Internal.EntityWrapperWithoutRelationships 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 1.<> c__DisplayClassd.b__c()      at System.Data.Entity.Internal.Linq.InternalSet 1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet 1.Add(Object entity)      在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上,这是一个int数组,你可以在堆栈跟踪中看到它不是原因。我已经坚持了一段时间,并尝试了各种方法,如临时收集和使用AddRange或每次添加后保存上下文。

非常感谢任何有关问题所在的帮助。

1 个答案:

答案 0 :(得分:2)

附件还收藏?如果它来自任何db对象,则在分配时尝试调用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)
            });
        }