title: What steps to get rid of Collection was modified; enumeration operation may not execute. Error?
body: <p>Our programming involves some Mock testing using  In-Memory Data.  Therefore, we implemented the following code that would first create In-Memory Data of Customer objects</p>
  
  <pre><code>        // Let us create some in-memory data
          // Create a list of Customer
          List&lt;Customer&gt; listOfCustomers =  new List&lt;BlahBlahExample.Domain.Objects.Customer&gt;()
                                     { new Customer { CustomerID = "1    ",Orders = new HashSet&lt;Order&gt;(), CustomerDemographics = new HashSet&lt;CustomerDemographic&gt;(), CompanyName = "Chicago Bulls", ContactName = "Michael Jordan", ContactTitle = "top basket ball player", Address = "332 testing lane", City = "Chicago", Region = "Illinois", PostalCode = "484894", Country = "USA", Phone = "3293993", Fax = "39393" },
                                       new Customer { CustomerID = "2    ",Orders = new HashSet&lt;Order&gt;(),CustomerDemographics = new HashSet&lt;CustomerDemographic&gt;() , CompanyName = "Miami Heat", ContactName = "Lebron James", ContactTitle = "second best basket ball player", Address = "90 test street", City = "Miami", Region = "Florida", PostalCode = "4869394", Country = "USA", Phone = "3293213", Fax = "33393" },
                                       new Customer { CustomerID = "3    ",Orders = new HashSet&lt;Order&gt;(),CustomerDemographics = new HashSet&lt;CustomerDemographic&gt;() , CompanyName = "Oklahoma City Thunder", ContactName = "Kevin Durant", ContactTitle = "current top basket ball player", Address = "35 test row", City = "Oklahoma City", Region = "Oklahoma", PostalCode = "480290", Country = "USA", Phone = "304923", Fax = "33325" }
                                     };
  
  
          // Convert the list to an IQueryable list
          IQueryable&lt;Customer&gt; queryableListOfCustomerInMemoryData = listOfCustomers.AsQueryable();
  
  
  
          // Let us create a Mocked DbSet object.
          Mock&lt;DbSet&lt;BlahBlahExample.Domain.Objects.Customer&gt;&gt; mockDbSet = new Mock&lt;DbSet&lt;BlahBlahExample.Domain.Objects.Customer&gt;&gt;();
  
          // Force DbSet to return the IQueryable members
          // of our converted list object as its 
          // data source
          mockDbSet.As&lt;IQueryable&lt;BlahBlahExample.Domain.Objects.Customer&gt;&gt;().Setup(m =&gt; m.Provider).Returns(queryableListOfCustomerInMemoryData.Provider);
          mockDbSet.As&lt;IQueryable&lt;BlahBlahExample.Domain.Objects.Customer&gt;&gt;().Setup(m =&gt; m.Expression).Returns(queryableListOfCustomerInMemoryData.Expression);
          mockDbSet.As&lt;IQueryable&lt;BlahBlahExample.Domain.Objects.Customer&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(queryableListOfCustomerInMemoryData.ElementType);
          mockDbSet.As&lt;IQueryable&lt;BlahBlahExample.Domain.Objects.Customer&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(queryableListOfCustomerInMemoryData.GetEnumerator());
          mockDbSet.Setup(m =&gt; m.Add(It.IsAny&lt;Customer&gt;())).Callback&lt;Customer&gt;(listOfCustomers.Add);
  
  
          Mock&lt;BlahBlahAuditMappingProvider&gt; jsAudtMppngPrvdr = new Mock&lt;BlahBlahAuditMappingProvider&gt;();
          Mock&lt;BlahBlahDataContext&gt; fctry = new Mock&lt;BlahBlahDataContext&gt;(jsAudtMppngPrvdr.Object);
          Mock&lt;BlahBlahDataContext&gt; qryCtxt = new Mock&lt;BlahBlahDataContext&gt;();
          Mock&lt;BlahBlahAuditContext&gt; audtCtxt = new Mock&lt;BlahBlahAuditContext&gt;();
  
  
           Mock&lt;BlahBlahDataContext&gt; mockedReptryCtxt = new Mock&lt;BlahBlahDataContext&gt;();
  
  
           mockedReptryCtxt.Setup(q =&gt; q.Customers).Returns(mockDbSet.Object);
  
  
          mockedReptryCtxt.Setup(q =&gt; q.Set&lt;Customer&gt;()).Returns(mockDbSet.Object);
  
  
          mockedReptryCtxt.CallBase = true;
  
  
          DbSet&lt;Customer&gt; inMemoryDbSetCustomer = mockedReptryCtxt.Object.Set&lt;Customer&gt;();
  </code></pre>
  
  <p>In the next excerpt of code( which is our "Code Under Test"), I add a new Customer to the existing In-Memory Data, and then Invoke SaveChanges on the Mocked Object.</p>
  
  <pre><code>                    Customer returnCust = (Customer)(mockedReptryCtxt.Object.Set&lt;Customer&gt;().Add(new Customer { CustomerID = "4    ", Orders = new HashSet&lt;Order&gt;(), CustomerDemographics = new HashSet&lt;CustomerDemographic&gt;(), CompanyName = "Kolkota Knights", ContactName = "Sachin Tendulkar", ContactTitle = "current top cricket player", Address = "35 test row", City = "Kolkota", Region = "West Bengal", PostalCode = "3454534", Country = "India", Phone = "304923", Fax = "33325" }));
  
              mockedReptryCtxt.Object.SaveChanges();
  </code></pre>
  
  <p>Later on in the code, I have the following excerpt of code where _context.Set() will return the In-Memory Data DBSet that we created previously</p>
  
  <pre><code>        var query = _context.Set&lt;TEntity&gt;().AsQueryable();
  
          if (typeof(TEntity).Name.Contains("Audit"))
          {
              return query;
          }
  
          if (includes != null &amp;&amp; includes.Any())
          {
              foreach (var include in includes)
              {
                  query = query.Include(include);
              }
          }
  
  
          List&lt;TEntity&gt; resultsAsList = query.ToList(); // Error Thrown When using ToList()
  
         var results = resultsAsList.AsQueryable();
  </code></pre>
  
  <p>When we invoke ToList(), it Throws the following Error:</p>
  
  <pre><code>System.InvalidOperationException was unhandled by user code
    HResult=-2146233079
    Message=Collection was modified; enumeration operation may not execute.
    Source=mscorlib
    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.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
         at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
          at BlahBlah.Framework.EntityFramework.EntityFrameworkRepository`1.ConcreteQuery(List`1      includes) in d:\EMIS\BlahBlah       Framework\BlahBlahFrameworkLightweight\BlahBlah.Framework.EntityFramework\EntityFrameworkRepository.c     s:line 51
          at Castle.Proxies.EntityFrameworkRepository`1Proxy.ConcreteQuery_callback(List`1 includes)
          at Castle.Proxies.Invocations.EntityFrameworkRepository`1_ConcreteQuery.InvokeMethodOnTarget()
         at Castle.DynamicProxy.AbstractInvocation.Proceed()
          at Moq.Proxy.CastleProxyFactory.CallContext.InvokeBase()
          at Moq.InvokeBase.HandleIntercept(ICallContext invocation, InterceptorContext ctx,     CurrentInterceptContext localctx)
          at Moq.Interceptor.Intercept(ICallContext invocation)
          at Moq.Proxy.CastleProxyFactory.Interceptor.Intercept(IInvocation invocation)
          at Castle.DynamicProxy.AbstractInvocation.Proceed()
          at Castle.Proxies.EntityFrameworkRepository`1Proxy.ConcreteQuery(List`1 includes)
           at BlahBlah.Framework.Core.Repository.BaseRepository`1.Query(List`1 includes) in      d:\EMIS\BlahBlah      Framework\BlahBlahFrameworkLightweight\BlahBlah.Framework.Core\Repository\BaseRepository.cs:line 149
           at Castle.Proxies.EntityFrameworkRepository`1Proxy.Query_callback(List`1 includes)
           at Castle.Proxies.Invocations.IRepository`1_Query.InvokeMethodOnTarget()
           at Castle.DynamicProxy.AbstractInvocation.Proceed()
            at Moq.Proxy.CastleProxyFactory.CallContext.InvokeBase()
          at Moq.InvokeBase.HandleIntercept(ICallContext invocation, InterceptorContext ctx,      CurrentInterceptContext localctx)
           at Moq.Interceptor.Intercept(ICallContext invocation)
            at Moq.Proxy.CastleProxyFactory.Interceptor.Intercept(IInvocation invocation)
           at Castle.DynamicProxy.AbstractInvocation.Proceed()
          at Castle.Proxies.EntityFrameworkRepository`1Proxy.Query(List`1 includes)
           at      BlahBlah.Test.Unit.CntrlrsTests.CustomerControllerTest.Test_Creation_Of_Customer_Using_Constructor_Of     _Customer_Controller_That_Expects_Arguments() in d:\EMIS\BlahBlah      Framework\BlahBlahFrameworkLightweight\BlahBlah.Test.Unit\CntrlrsTests\CustomerControllerTest.cs:line       278
      InnerException: 
  </code></pre>
  
  <p>What steps do we need to take in order to stop the said error from being thrown( preferably without Changing too much of our Code Under Test)?</p>