Bobby Tables
Bobby Tables

Reputation: 3013

Collection was modified; enumeration operation may not execute MVC

I keep getting this error : Collection was modified; enumeration operation may not execute

protected void SendAddedMessages(IEnumerable<int> receiverIds, Result result)
{
    foreach (var receiverId in receiverIds)
    {
        SendAddMessage(receiverId, result);
    }
}

I understand what it means but the problem is that as you can see i'm not modifying it anywhere, the call to my function is SendAddedMessages(result.People.Select(r => r.Id), result);

I think i can just cast it as an array and just use a for loop but what i want to know it where/why is it modified. This is an MVC application and i'm using EntityFramework, could there be another thread doing this ?

Update 1 added the SendAddMessage

protected void SendAddMessage(int recevierId, Result result)
{
    Messaging.SendMessage(
            recevierId,
            "Some text",
            String.Format(CommonString.AddedToResult, result.Name, Name)
        );
}

Upvotes: 2

Views: 846

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109079

The only thing I can think of is that the content of the database table changes during the (probable relatively lengthy) process of sending mails. The db reader is reading while the collection is enumerated and prior to EF6 this read is not from a snapshot by default. See Entity Framework 6: The Ninja Edition, look for READ_COMMITTED_SNAPSHOT.

That's why it's always good practice to take control over when a query is actually executed and to execute it quickly. Personally, I'd prefer an argument like ICollection<int> receiverIds, so I know that I receive an enumerated collection, not a lazy loading bomb.

EDIT
After your final comment, saving objects that are related to People may cause collections to modify deeper in EF's machinery, because EF will also run DetectChanges, which may touch existing associations.

Upvotes: 2

Related Questions