Skip to content

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

Robert Greiner
Robert Greiner
1 min read
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.

Please consider subscribing, it's free.
Technology

Robert Greiner Twitter

Professional optimist. I write a weekly newsletter for humans at the intersection of business, technology, leadership, and career growth.


Related Posts

Members Public

AI Rule #1 - Customer First

In 1985, Warren Buffett wisely said, "The first rule of investment is don't lose. And the second rule of investment is don't forget the first rule, and that's all the rules there are." Similarly, the first rule of AI investment is to

AI Rule #1 - Customer First
Members Public

Navigating the Upside Down as a Technology Leader

Ideas for leading technology organizations with confidence and creativity.

Navigating the Upside Down as a Technology Leader
Members Public

Artist for a Day

The future of creative output is multiplied by AI.

Artist for a Day