Does Entity Framework store it's DbContext along with cached query plans?
In my web application, we are using a per request DbContext. We create the DbContext in Application_BeginRequest(), store it in HttpContext.Items, and then call Dispose on it in Application_EndRequest().
We make the current context available through a wrapper class DatabaseContext.Current property.
Sporadically, when executing a query against this database context, we get the following exception:
"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection".
I've searched our code for any possibility that we are calling Dispose on the context elsewhere....we aren't.
A query that commonly fails is开发者_StackOverflow中文版 this one:
var user = (from u in DatabaseContext.Current.Users
where u.UserName == username
select u).FirstOrDefault();
return user != null;
All I can think of is that deep in the bowels of the EF it is keeping a reference to the DbContext in a cached query plan and then attempting to reuse that context when the query is executed. I've looked at it through reflector and it does seem that some of the internals keep a reference to the ObjectContext.
Is there a way to disable linq query caching? Anyone have any clues?
The other possibility is that a query from a previous call on the Context is leaving the Context in bad state. However, there are no indications of failures that would indicate this.
This is Entity Framework 4.1 using Sql CE (for now, we are soon migrating to a production SQL Server Instance).
Neither of your scenarios should happened. There is no caching you mentioned. There are some possibilities you should check instead:
- You are using context after
EndRequest
or outside of currentHttpRequest
scope - You are storing entity retrieved from context somewhere in cache or session and using it in other request processing - this can be an issue because entity can keep reference to disposed context and use it for some operations.
There is no automatic LINQ query caching - it is feature planned for upcoming EF release but that feature caches DbCommand
instances independent on the context.
You get this exception "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" - because there is a failed transaction, after that trying to access a data query. Put a try catch and observe the exception. precisely, there is an exception, which is not handled properly.
精彩评论