流畅的NHibernate会话异常处理

时间:2015-02-26 11:13:15

标签: c# nhibernate fluent-nhibernate

如何在会话期间处理NHibernate异常?互联网上有很多例子:

http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-exceptions https://svn.code.sf.net/p/nhibernate/code/trunk/nhibernate/src/NHibernate/ISession.cs

许多StackOwerflow线程提出了类似的方法:

using (ISession session = factory.OpenSession())
using (ITransaction tx = session.BeginTransaction())
    {
        try
        {
            // do some work
            ...
            tx.Commit();
        }
        catch (Exception e)
        {
            if (tx != null) tx.Rollback();
                throw;
        }
    }

但是如果发生错误并且在第1行代码上抛出异常(当你打开会话时)会怎么样?这些例子都没有掩盖它!

我的一个人大肆吹嘘这种方法:

ITransaction transaction = null;
    try
    {
        using (ISession session = databaseFacade.OpenSession())
        {
            transaction = session.BeginTransaction();
            //do some work
            ...

            transaction.Commit();
        }
    }
    catch (Exception ex)
    {
        if (transaction != null)
            transaction.Rollback();

        throw new Exception(ex.Message);
    }

1 个答案:

答案 0 :(得分:1)

我建议解耦组件

  • 公开会议
  • 执行数据库操作

使用这种方法,您可以保留在第1行内处理OpenSession()例外的逻辑,以后不用担心。原因是,如果(在您的情况下)databaseFacade.OpenSession()抛出异常,您不必抓住它并检查transaction,因为它必须是null

    //if OpenSession() throws it's fine , not transaction at all
    using (ISession session = databaseFacade.OpenSession())
    {
        using (ITransaction tx = session.BeginTransaction())
        {
          try
          {
              // do some work
              ...
              tx.Commit();
          }
          catch (Exception e)
          {
            //tx is not null at this point
            tx.Rollback();
            throw;
          }
        }
    }