tags:

views:

91

answers:

2

Hello,

I am a little bit confused with NHibernate and Session. As I understood, I am supposed to use sessions "as quickly as possible", meaning that two different interactions get their own session.

What do I do in case of UI interactions, I want to store in the DB. I have a simple example, where a treeview lists some items, and is bound to the IsExpanded property of my business objects (I know, bad practice, but for my approach its ok)...

The question now is, when do I save the changes. Currently I am flushing manually when the window is closed, it does not quite seem right. I could flush everytime a property is changed, but that is complete overkill, I think.

Is there some pattern or tips for this kind of problem. Kind of "tidy up and store GUI infos at the right moment"...

Here is some code for better understanding:

    private static PjmDbController _d;
    private static IList<Topic> _allItems;

    private static void TopicStoresChildStatesExpandedOrNot()
    {
        var w = new Window();
        _d = new PjmDbController();
        _allItems = _d.GetAllRoots();
        w.Content = new PjmTreeView<Topic>() {ItemsSource = _allItems};
        w.Show();
        w.Closed += new EventHandler(w_Closed);
    }

    static void w_Closed(object sender, EventArgs e)
    {
        _d.Session.Flush();
    }

Thanks for tips, Chris

PS: The static is only for testing :-)

+2  A: 

This should all tie into when the user would normally select their save operation (i.e. via a 'Save changes' button, or a confirmation of save when they exit the form).

(As an addendum) in cases where you do want live persistence happening without user intervention (i.e. saving state in a game, etc.) then one pattern is to use time-based queueing, so on a change operation, if the last save was more than X seconds ago, persist your objects - since a save on every single change can be overkill based on volume.

Bob Palmer
+1  A: 

It depends entirely on the scope of a unit of work in the application. A best practice with NHibernate is to treat the session as a unit of work. If opening the form, manipulating the tree, and closing the form represents a single unit of work then it makes sense to flush the session when the form is closed. I would, however, persist the changes inside a transaction rather than flushing the session. This answer is good advice about managing the session.

Jamie Ide