Tech Talk A software developer on all things tech, and then some

9Mar/120

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();
            }
Comments (0) Trackbacks (0)

No comments yet.


Leave a Reply

No trackbacks yet.

%d bloggers like this: