RepositoryBase: delete method "Collection was modified; enumeration operation may not execute"

May 25, 2012 at 2:31 PM

Hi folks, if someone has this error deleting a record from a repository, I have adopted this solution:

Error:

Collection was modified; enumeration operation may not execute

Solution:

public virtual void Delete(Expression<Func<T, bool>> where)
{
       var objects = _dbset.Where(where).AsEnumerable();
       foreach (var obj in objects.ToList())
                _dbset.Remove(obj);
} 

I've converted ToList(). It works fine.

If anyone has a better solution, here I am to hear it! Perhaps with a huge amount of data this might become too slow.