Entity framework - objectcontext disposed exception

Mitulát báti picture Mitulát báti · Mar 18, 2013 · Viewed 11.1k times · Source

I've been debugging this program without any result, and unfortunately I can't see the root of the problem. I get this exception: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

There are 2 tables: - CustomerSet - OrderSet

A field named Customer_id in the Orders table ensures the relationship between the tables, and there is a virtual navigation property called Customer in the Orders table as well.

The scenario is the following: I insert an element into the Orders table:

Order order = new Order();
Order.order_id = GenerateId(IdType.Order);
Order.date = DateTime.Now;
Order.Customer_id = GetCustomerId(tbCustomerName.Text);
Insert(order);

Within the Insert method there is DBContext in a using statement, so it automatically dispose when needed. I work inside this.

After that, I need data from the previously inserted element (for instance, I need some property of the Customer field). And now I'm hoping that the Customer field got value:

Order o = GetOrder(order.order_id);

And I got this o with an exception in the Customer field: o.Customer threw an exception of type 'System.ObjectDisposedException'

I was playing with lazy loading, turning it on or off, but I didn't work out. The situation is the same...

What do I make a mess with?

What is real nice in this, that if I go step-by-step with F11, it often works correctly!

Please help! Thank you in advance.

Answer

Eric J. picture Eric J. · Mar 18, 2013

Within the Insert method there is DBContext in a using statement, so it automatically dispose when needed

Not exactly "when needed". It calls IDisposable.Dispose() on the context object as soon as it goes out of scope of the using block.

After that, I need data from the previously inserted element

Your context is disposed at this point. If your action requires lazy loading, that will fail because the context is not available to perform the lazy load.

If you will generally need access to an object that has not been loaded, the most efficient approach is probably to use .Include to load it when you retrieve the rest of your object graph. That is called eager loading.

If you occasionally need access to an object that is not loaded when you load the rest of your object graph, you will need a new context.

For a discussion of loading related objects, I suggest

http://msdn.microsoft.com/en-us/data/jj574232.aspx