Should I store view models or domain models in session?

267 views Asked by At

Am a little confused about session state storage. I have an MVC application, there are view models, which are closer to the view, then there are the domain models which have rich behavior. We are required to store some session state in our application and am having a hard time deciding if I should store my view models or my domain models in my session.

We inherited a legacy application and we are forced to extend a ViewModelBase which has a lot of cruft in it. Hence am hesitant to save the view models in session. On the other hand, domain models have behavior in them and it doesn't feel right to store them.

Any ideas?

1

There are 1 answers

3
Chris Pratt On

I would say neither. First, use of the session should be avoided as much as possible. Second, storing objects in the session can be very problematic. Unless you're using in-proc session storage (which you shouldn't), then every other session backing will require that the objects be serialized. For simple classes, that's not too bad, but if you're dealing with hierarchies and object graphs, then it's going to be a ridiculously huge pain.

You haven't given any information about what you're actually trying to accomplish other than just "we are required to store some session state". Required by who or what and why? Perhaps, if you ask about what you're actually trying to do, someone can give you a better solution that doesn't involve sessions at all, or at least only minimally. For example, instead of storing the entity, could you not simply store the id, and use that to pull the entity from the database?