0

I read the questions regarding to such error message had been raised a few dozen times in SO,

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

however, my scenario might had not been covered.

I am maintaining a legacy WPF app with EF 6, code first and lazy loading. Each window has its own ViewModel which contains a long live DbContext object created in the constructor. So basically the context will buffer all changes until the users press the Save button. Each window contains a master list and details, related to the master/details structure in DB, and the details are loaded through lazy loading.

The ViewModel is wired into the View through such XAML codes:

    <UserControl.DataContext>
    <vm:CustomersViewModel></vm:CustomersViewModel>
</UserControl.DataContext>

The program basically works well, however, after a few hours of idle, when the user click on the master list to navigate to another record, this error will popup up.

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

The DbContext apparently is not disposed, since it was created in the ViewModel of the windows, and should be disposed only when the window is closed through the IDisposale pattern. I would suspect ObjectContext inside DbContext is disposed after some idle time.

While I understand the common usage of DbContext is to contain in the using clause to make sure short live, however, it will be difficult for me to change to legacy design now. I just wonder if there exist ways to keep DbContext / ObjectContext alive

ZZZ
  • 2,752
  • 2
  • 25
  • 37
  • seems like the underlying connection has been disposed, you may perhaps catch such errors and re-initiate the connection if needed. – pushpraj Sep 18 '14 at 03:51
  • Do you mean that the connection object used by DbContext get disposed by someboday when idle? The exception is actually caught by some sort of uncaught exception handler and displayed. However, it is hard to return back to the point where the exception was raised. Catching such exception everywhere seems to be expensive. – ZZZ Sep 18 '14 at 04:09
  • then perhaps apply some keep alive techniques or ideally create only when you need it. refer to this answer http://stackoverflow.com/questions/3194185/ef-and-repository-pattern-multiple-contexts & [Entity Framework ObjectContext re-usage](http://stackoverflow.com/questions/2724176/entity-framework-objectcontext-re-usage) – pushpraj Sep 18 '14 at 04:15

0 Answers0