views:

42

answers:

3

Hi,

I want to present you my windows forms application scenario:

I want to create an invoice, so I open new window with invoice details. Then I want to add new customer (to the database), that I want to use in my invoice. After entering all the information (including new customer info) I click Save to save my new document.

The question is: should I do all the work in one NH session? So saving new customer and saving invoice in one unit of work.

Or maybe saving new customer should be done separately? If yes, then if I add new customer and click cancel in invoice details form, then invoice creation is canceled, but customer is still in database.

I use one unit of work for the whole conversation. Maybe I'm wrong.

Regards, Chris

A: 

Logically, it would make sense to create the customer in a Unit Of Work and then create the invoice in another one. However, seeing as you seem to want the customer and invoice creation together to be atomic, it makes sense to have them created in one commit.

I don't know how NHibernate deals with the associations though - if the customer needs to be persisted already in order to associate it with the invoice, then you have no choice but to commit the uow after creating the customer and then create the invoice.

SnOrfus
A: 

should I do all the work in one NH session? So saving new customer and saving invoice in one unit of work.

Yes, use one NHibernate session. Mapping the life time of the session to a single unit of work is generally the easiest way to go.

Don't confuse sessions with transactions. If you want to rollback both creations if one creation fails, that requires a transaction and has (mostly) nothing to do with the NHibernate session.

Michael Maddox
Thanks.I've read about a solution, where you have in this case one UoW, so one NH session (with FlushMode.Never) and many NH transactions in every request. Every transaction should be commited after request is done properly, but don't use ISession.Flush(). So don't worry - commiting the transaction when ISession.FlushMode is set to 'Never' won't affect the database.To do the changes to the database after UoW is done, just run Session.Flush().Chris
Chris
It is called "session-per-conversation" pattern.
Chris
A: 

Conversation per business transaction is your friend:

The code is in unhaddins, and we have two examples for desktop applications. One of them is my "Chinook Media Manager" (look for the posts on google). There is also an implementation using PostSharp in unhaddins's trunk.

José F. Romaniello