I've been playing with various ideas for the above, and reading the various posts on session management under winforms in the forums here, and I'm thinking of going with the approach outlined below. I'm interested in any observations people might have. It's not rocket science, but I don't want to shoot myself in the foot further into the project.
1) If a form is displaying an entity read only, I open a session, load the entity and any related objects the form displays, then immediately close the session. If a form has multiple tabs I'll attempt to take advantage of lazy loading by delaying the setting of the datasource for each tab until the user enters that tab, and before setting it I will open a new session, Lock the parent entity and initialise any objects for that tab. Once that's done I'll close the session and set the data binding.
2) For an editable form it seems like nhibernate and data binding don't really get on. I think I have two choices:
a) Open a session when the form enters edit mode, and use it to load the object. Keep that session open until the user hits the save button. I can't load and close, then when the user presses save open and lock since the object will have changed by this point and nhibernate will throw an exception
b) Open a session, load the object, and close the session. Bind to the object. When the user hits save open a new session, load the object again, and copy the changed properties of the object (and all its related objects) back into the new object. Then flush and close the session
Option a) has the advantage of being fairly simple to manage, but the session needs to be open for a potentially long time. Data may be stale by the time the user hits save, but we can code for this. Option b) seems cleaner, but has several potential problems, I think:
i) I lose concurrency checking - since I reload the object on save, and copy over any changed fields, the system won't detect any conflicts with edits done by other users between loading and saving.
ii) I lose lazy loading, since the whole object graph must be loaded before any binding is done
iii) The code to copy back the object could be quite complex. I've written something in codesmith to generate it for me, but even so.
I guess a variant on b) that would solve the first issue might be to bind to a copy of the just loaded object, then on save lock this object again and copy the changes into there - I assume this would then detect any changes between loading and saving the original object?
On balance I'm thinking of option a), but will I regret it later?
Kev
|