6

I was wondering if it was wise to cache the Entity Framework's ObjectContext object in the Cache; will this give me issues with multiple connections at the same time that the user will experience issues with that?

I've gotten errors like: 'connection is currently closed' and wondered if that was due to multiple users and caching the ObjectContext, or if it was related to say hitting refresh multiple times or stopping the page and quickly doing something else (something that we did do to get the error).

2
  • Do you only read information or are you using the Save method as well? Commented Feb 8, 2010 at 22:02
  • I do both read/write with it. Commented Feb 9, 2010 at 14:03

2 Answers 2

6

I agree with above. However, I do cache the object context in HttpContext.Current.Items collection without any issues. Also a good read:

http://dotnetslackers.com/articles/ado_net/managing-entity-framework-objectcontext-lifespan-and-scope-in-n-layered-asp-net-applications.aspx

Sign up to request clarification or add additional context in comments.

Comments

5

I wouldn't advise it. The ObjectContext needs to be active to observe changes to any entities you are actively working with or you'd need to disconnect any active entities prior to caching the ObjectContext.

If you have no active entities, then there's no real need to cache an ObjectContext. In EFv1 working with disconnected entities was problematic at best, so I'd either not cache or wait for the Entity Framework v4 which allows for more manageable entities (self tracking entities, POCO entities etc).

Just thought I'd add one last point - multiple threads - could be problematic as well. Applying Changes will attempt to commit all changes tracked by the ObjectContext. If multiple users are sharing a single Context... well, hopefully you can see the problems..

3 Comments

Thanks, so without caching the context, do you recommend detaching entities returned from the queries too?
Also, what about if I use HttpContext.Current.Items collection, which only stores it for the current request? I'm not sure if that's global across users, but is that another similar concern? Thanks.
Sorry about the late reply - currently on the road. Detaching could work provided the original context is disposed properly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.