Entity Framework: There is already an open DataReader associated with this Command which must be closed first
**Still relevant since 2012:** I'm glad you're one of the thousands who find this post helpful. If you enjoy this article, I'd love for you to stick...
Still relevant since 2012: I’m glad you’re one of the thousands who find this post helpful. If you enjoy this article, I’d love for you to stick around and check out some of my more recent writing on technology, leadership, strategy, and AI. Explore recent posts →
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.
If you found this helpful…
I’ve spent the last decade moving from hands-on engineering to executive leadership, and I write about that journey.
If troubleshooting database and systems issues interests you, you might enjoy my writing on:
- Move Fast and Don’t Break Things - Building reliable systems
- The Simplicity Paradox - Managing technical complexity
- Navigating the Upside Down as a Technology Leader - Technical leadership insights
Want insights on technology strategy and engineering leadership? Subscribe for updates →
How did you like this article?
Enjoyed this article? Subscribe to get weekly insights on AI, technology strategy, and leadership. Completely free.
Subscribe for Free