Storing Object Hierarchies in the Session

Storing Object Hierarchies in the Session

Old forum URL: forums.lhotka.net/forums/t/775.aspx


Jav posted on Monday, July 31, 2006

Asp 2.0

Let's say that I have a Customer hierarchy with a CustomerProfile object(root), Person object, AddressCollection, and PhoneCollection.

In my Session("CurrentObject") I place the Root (CustomerProfile) along with the Child collections etc. 

My expectation is that as long as my Session does not time out, my Session("CurrentObject") will always return the root object of my hierarchy - even if I move from one page to the next.  Is that not the correct assumption?  It appears that the book (VB p 542) seems to imply that going from page to page will change the Session("CurrentObject") - or may I reading it wrong?

Jav

RockfordLhotka replied on Monday, July 31, 2006

Session is just a dictionary of objects, nothing more. So if you don't remove or change the item corresponding to a specific key (such as "CurrentObject") then that item will remain there unless your session times out or ASP.NET recycles the AppDomain or something.

My point in the book is that the code in each page of the app does overwrite the "CurrentObject" item as the user navigates from page to page. My goal in doing this was to minimize the amount of data in Session by only keeping the current object.

You can use Session in many other ways - you certainly don't need to do what I did in the book. Or you can implement a purely stateless model where you avoid using Session entirely in favor of reloading the object from the database.

Someone else, in a different thread, asked about keeping multiple objects in Session. That is fine - just don't follow the code I put into the pages in the book. My goal, again, was very clear and simple: use Session as a limited per-page cache. If the user moves to another page, Session starts holding the object for that new page. If they navigate back to the previous page, Session reloads the object for that previous page (obviously losing any in-memory data that might have been there).

This model typically works fine in the web, because navigating from one page to the next almost always entails saving the data. Clicking back to a previous page does not save the data. My approach in the book follows this general pattern, while minimizing data in Session to a large degree.

Copyright (c) Marimer LLC