Search code examples
c#asp.net-core-2.2ef-core-2.2ddd-repositories

Collection was modified; enumeration operation may not execute. EF Core 2.2


i need some help with this problem, i using EF Core 2.2 and ASP.Net Core 2.2

i'm trying to delete some phones from my entity (User) but when execute dbcontext.SaveChanges() generate a exception: Collection was modified; enumeration operation may not execute.

My UserService

User entity = _userRepository.GetById(model.Id);

var numbers = GetDeletePhoneNumbers(model, entity.UserPhones.ToList());

foreach (var number in numbers)
{                
   entity.RemoveUserPhones(_userPhoneRepository.GetByPhoneNumber(number));

   _userRepository.Modify(entity);
}

My method to get delete's Phones

 private List<string> GetDeletePhoneNumbers(UserModel model, List<UserPhone> userPhones)
 {
    return userPhones.Where(c => !model.Phones.Any(u => u.Number == c.Phone.Number)).Select(c => c.Phone.Number).ToList();
 }

And my RepositoryClass

protected override void InternalModify(TEntity entity)
{           
    this._dbContext.Set<TEntity>().Update(entity);
    _dbContext.SaveChanges();           
}

my StackTrace of the Exception

System.ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() at System.Collections.Generic.Dictionary2.ValueCollection.Enumerator.MoveNext() at System.Linq.Enumerable.ConcatIterator1.MoveNext() at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()

ty for the help...


Solution

  • The issue is that foreach loops assume an immutable collection to iterate over it. That is, the collection can't be modified while the loop is happening; in other words, the collection when the loop begins must remain the same throughout the loop's execution.

    Therefore, modifying the state of the collection while the loop is happening causes an exception to be thrown. This has nothing to do with EF, it's a characteristic of the foreach loop.