ADO.NET Entity Framework ObjectContext - Caching Question
Asked Answered
M

2

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

Mulry answered 8/2, 2010 at 21:56 Comment(2)
Do you only read information or are you using the Save method as well?Frothy
I do both read/write with it.Mulry
F
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

Fuzz answered 10/2, 2010 at 0:4 Comment(0)
G
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..

Galibi answered 8/2, 2010 at 22:5 Comment(3)
Thanks, so without caching the context, do you recommend detaching entities returned from the queries too?Mulry
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.Mulry
Sorry about the late reply - currently on the road. Detaching could work provided the original context is disposed properlyGalibi

© 2022 - 2024 — McMap. All rights reserved.