views:

550

answers:

2

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).

+4  A: 

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..

RobS
Thanks, so without caching the context, do you recommend detaching entities returned from the queries too?
Brian
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.
Brian
Sorry about the late reply - currently on the road. Detaching could work provided the original context is disposed properly
RobS
+3  A: 

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

itchi