The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Have you ever assigned a value to an IEnumerable from a database, then try to access in a foreach or something similar and get the following?

“ObjectDisposedException was unhandled by user code : The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.”

If you are using a using statement with your entity context, then most likely you are returning an IEnumerable, which builds a list on the fly from the database, versus a List which will return the whole entire set at once. So you will be able to get a single item from the database before the connection closes vs obtaining a collection/list of the data required. To do this, add a ToList() to the end of your enumeration when returning in your using statement. For example :

            using (CarEntities dbContext = new CarEntities ())
            {
                return dbContext.CarModels;
            }

Would change to the following… Really as simple as adding the .ToList()

            using (CarEntities dbContext = new CarEntities ())
            {
                return dbContext.CarModels.ToList();
            }

Jacob Saylor

Software developer in Kentucky

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: