NHibernate - Best Practice for Easy Choice

A have an action in my MVC application that has idand returns the name of the person.

What is the best practice for this? I follow the advice of NHProf, but the 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();
    }
}
+5
source share
3 answers

The NHProf warning page explains this pretty well, I think -

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

Basically, saying that you yourself do not manage transactions, the database will create an "implicit transaction" and automatically commit for each operator, including requests. The misconception is that transactions are only useful for insert / update operations.

, . , .

+4

The following is an example of how I would approach this choice:

    using (var session = Helper.SessionFactory.OpenStatelessSession())
    using (var tran = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        try
        {
            string personName = session.Query<Person>()
            .Where(x => x.Id == id)
            .Single(x => x.Name);

            tran.Commit();
            return personName;
        }
        catch(Exception ex)
        {
            // handle exception
            tran.Rollback();
        }
    }

This SO answer gives good advice for making transactions:

NHibernate - Is ITransaction.Commit Really?

As for your LINQ, this is an interesting article on how not to approach queries using extension method style syntax:

http://compiledexperience.com/blog/posts/how-not-to-use-linq

-1
source

All Articles