Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate - Best Practice for just select

A have an action on my MVC application that have an id and returns a person's name.

What is the best practice for that? I'm following NHProf tips, but code sounds a little strange or something for me.

using (var session = Helper.SessionFactory.OpenStatelessSession())
{
    using (var tran = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        return session.Query<Person>().Where(x => x.Id == id).Select(x => x.Name).SingleOrDefault();
        tran.Rollback();
    }
}
like image 795
Zote Avatar asked Oct 07 '22 20:10

Zote


1 Answers

The NHProf alert page explains it quite well I think -

http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactions

Basically it's saying if you don't manage transactions yourself, the database will create an "implicit transaction" and auto-commit for every statement, including queries. The misconception is that transactions are useful only for insert / update operations.

In your example above, it's not much of an issue as your transaction only executes a single statement anyway. If your method was running several statements however it would be good practice to wrap them in a transaction.

like image 79
richeym Avatar answered Oct 12 '22 10:10

richeym