1
votes

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.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)

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.

1
Your error must be coming from statement Folder = db.Folders.Find(folderId)Satpal
How folderIds are being initialized?Jenish Rabadiya
Folder is a virtual property in your entities Am I right? if yes then you no need to assign value for that.Chandrasekar Kesavan
@Setpal I also think that is the source. But I haven't got a clue how to fix it :P JenishRabadiya I don't think that is the source of the issues. I tried to list, to array, or puttting it in a for loop which all had the same result. Chandru Yes it is a virtual property. But it has to be assigned somehow otherwise it will add a null, which is not what I want. I have tried db.Folders.Find(folderId).Mails.Add(new Mail....)Nick
It also throws the same exception when I set FolderId manually using a foreign key attribute in the model. Which should rule out the .find issue.Nick

1 Answers

4
votes

Attachments also collection? If it comes from any db object try to call ToList() when assigning.

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