【问题标题】:fluent NHibernate session exception handling流畅的 NHibernate 会话异常处理
【发布时间】:2015-02-26 19:21:27
【问题描述】:

在会话期间应该如何处理 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;
        }
    }

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

我的一所大学建议采用这种方法:

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);
    }

【问题讨论】:

    标签: c# nhibernate fluent-nhibernate


    【解决方案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;
              }
            }
        }
    

    【讨论】:

    • 如果 OpenSession() 抛出异常则事务不会发生是正确的,但是您如何处理该异常?在您的代码示例中,try catch 块不会处理它。还是我错过了什么?
    • @SomeGuy 如果OpenSession 失败,则无需处理任何内容,因为尚未创建任何内容。实际上你唯一应该做的就是重新抛出异常,因为很可能应用程序将无法工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 2012-06-28
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    相关资源
    最近更新 更多