Need help understanding Nhibernate Transactions and how not to duplicate code (if possible)
I understand that you should always use transactions. I also see that NHibernate.ITransaction implement a Dispose, so I need to wrap my ITransaction object in a using statement. So, does that mean that for every non-readonly repository method (i.e. update, edit...) I have to declare:
using (ITransaction _transaction = _session.BeginTransaction(//isolationlevel)) {
//procedure code here
}
Is there a way that I ca开发者_StackOverflown wrap this (I am not seeing that I can).
Also, is it best that I wrap both a session.SaveOrUpdate() method and transaction.Commit() in a Try/Catch?
using (_transaction = _session.BeginTransaction(IsolationLevel.ReadCommitted) {
try {
_session.SaveOrUpdate(entity);
try {
_transaction.Commit();
catch (//some exception ex) {
_transaction.RollBack();
}
}
catch (//some exception ex) {
//log ex
}
}
Or is there a better way such as having both session and transaction methods in the same try/catch?
Thanks,
The recommended practice when using the ISession directly is this: (you should use a transaction even for reads)
using(var session = factory.OpenSession())
using(var tx = session.BeginTransaction())
{
// all the code that uses the session goes here
// use session to load and/or save entity
}
This is basically creating an unit of work.
Depending on your operation context ( web request, wcf request ) you might want to have all the operation inside a single unit of work. For web request see this for WCF operation see this.
Also as Sixto Saez said calling SaveOrUpdate is a smell. In most of the cases you have one of these two cases:
1 You create a new entity and call session.Save(entity);
or
2 You get an entity or more from the session ( with Get/Load or by query ), modify the entity and the changes will be saved by nhibernate on session disposal. ( unless you change the session flush mode but that is not the point ).
I would steer clear of micro-managing the transaction within a repository like that. This post does a good job of explaining why adding database semantics to your repository is not a good idea when using NHibernate (or any other ORM). The best practice is to implement a unit of work pattern for your business logic.
精彩评论