This can be one of the most boring error to fix within Entity Framework code, but, once you know this trick, it will be very easy!

You get this error when your DataContext tries to retrieve a collection of objects from the database and then subsequently tries to write to an object in the same connection.

For 99% of the cases, you will be able to resolve this issue by wrapping your DataContext in a using block:

IEnumerable<Customer> customers;
using (var ctx = new CustomerContext())
{
  customers = ctx.AwesomeCustomers;
}

//Do this outside of the using block.
UpdateCustomerData(customers); 

However, this may not be an option for you if you are working on a particularly complicated project that leverages the Repository Pattern (or something similar) and shares a single DataContext instance throughout the object. If this is the case for you, then you need to make sure you force the DataContext object to completely finish the read operation before you try writing.

var customers = customerRepository.GetAwesomeCustomers().ToList();
UpdateCustomerData(customers);

ToList() forces the DataContext to complete the read operation, freeing the connection up to perform another action.

The bad side of this practice it’s that it will materialise the whole collection into memory which if you are dealing with large amounts of data.

Advertisements