views:

42

answers:

2

In my web application a Session is created in the BeginRequest handler. All database operations are performed against this session. In the EndRequest handler, the session is used to create a transaction which is then committed. Afterward, the session is disposed. This wraps all database operations performed against the session into a single transaction.

When is it beneficial to create a transaction to be committed within the request-transaction? How is this done?

In other words, for what reason would I create a transaction for any purpose other than to commit all the database operations performed in the current request?

+1  A: 

When a user visits a page, you want to log various things to the database - a Page Hit etc. This can happily occur on the same session but you want the page tracking to be flushed to the database, even if an error subsequently occurs.

For performance too, you will want to hold your transactions open for as short a time as possible. During your request you may be performing a lot of non-databased oriented operations during which time there is no reason to hold a transaction open.

Lots of other examples...

cbp
A: 

I'm personally not a fan of doing it this way for the simple reason of error handling. If your transaction.Commit fails on your main Action/Request/Whatever, you have no context as to what was going on. You are then left sending the user to some lame error page or something like that. This is especially true if you are doing web services where you may return a result code indicating internal error or something like that.

I find that I typically have one business transaction per call, therefore, I let my Application Service manage the transaction and just let the BeingRequest handle opening the Session and EndRequest to Flush the session and dispose.

The reason I flush on EndRequest is to handle any DB activities that may have happened outside a transaction boundary, however, this is more the case if you have a component for handling this across all your sites/services.

Corey Coogan