Introduction
Entity Framework: There is already an open DataReader associated with this Command which must be closed first
Technology

Entity Framework: There is already an open DataReader associated with this Command which must be closed first

EntityCommandExecutionException

{"There is already an open DataReader associated with this Command which must be closed first."}

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:

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.

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

Robert Greiner
Author

Robert Greiner

Professional optimist. Passionate about cultivating high-performing teams @ scale by integrating the timeless wisdom of the past with the marvel of today's emergent technology in a practical way.

View Comments
Next Post

404 Error when uploading large files into Windows Azure

Previous Post

Beware The Second System Effect

Subscribe for free

Subscribe to my newsletter and get the latest posts delivered right to your inbox for free. I don't spam and your email won't be shared with third-parties.

Thanks for subscribing!

Check your inbox to confirm your subscription.

Please enter a valid email address!