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:
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) at System.Collections.Generic.List
1.Enumerator.MoveNextRare() at System.Collections.Generic.List
1.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.InternalSet
1.<>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.InternalSet
1.Add(Object entity) at System.Data.Entity.DbSet`1.Add(TEntity entity)
This only occurs the second time a 'Mail' object is being added to the context The 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)
});
}
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.
Any help with where the problem lies will be much appreciated.
Folder = db.Folders.Find(folderId)
– SatpalfolderIds
are being initialized? – Jenish Rabadiya