views:

90

answers:

3

Hi,

I have been working with entity framework and ASP MVC for a while. I have stored the entity object in the HttpContext.Current.Session in order to use the same session at all times. Now I have encountered some problems and I am wondering if this may have been a bad idea and if so, how should I do it otherwise.

The problem I have now is that the entity object caches data and that one user cannot see changes that the other user has done.

+3  A: 

The session is basically a hash table-like structure that is specific to a user. If you want to store data that can be seen by all users of the system, you either want to use the Application scope or caching.

This article from MS covers the different options for state management, including session and application:

http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

Caching is slightly different in that it allows you to do things like set expiration. If you don't need this kind of functionality, I would recommend sticking with application state. Article on caching from MS:

http://msdn.microsoft.com/en-us/library/6hbbsfk6%28VS.71%29.aspx

Phil Sandler
+2  A: 

The problem with storing Entities in memory between requests / sessions or whatever is that you have to be very careful if you have a new ObjectContext for each request / session whatever, because and entity can only be attached to one ObjectContext at a time, and can be easy to forget to detach (between requests in the same session) or to correctly share an object (between concurrent requests in different sessions).

Check out this Tip for clues on how to cache data between requests / users / sessions etc.

Hope this helps

Alex

Alex James
I think he writes about storing ObjectContext in session and I would strongly discourage that, because ObjectContext is easy to be messed up. ObjectContext per request is my solution.
LukLed
+1  A: 

By the book you would want your object context exist the shortest time possible.

so you create a context, grab some data, return your view to client.

and dispose everything.

Start caching when your db can't handle your load.

Alexander Taran