C# don';t在发生异常后刷新会话

C# don';t在发生异常后刷新会话,c#,nhibernate,C#,Nhibernate,我明白了 我可以只使用try-catch和session.Close吗?在这个例子中,什么是更好的方法 范例 null id in FoodOrder.Core.Entities.Articles entry (don't flush the Session after an exception occurs) 异常发生后,会话处于无效状态,应立即释放。这就是您应该始终在事务中执行写入的原因之一。如果没有,您就不知道数据库的状态。因此,我建议: 您不会显式刷新数据,并且始终坚持数据访问(读取和

我明白了

我可以只使用try-catch和session.Close吗?在这个例子中,什么是更好的方法

范例

null id in FoodOrder.Core.Entities.Articles entry (don't flush the Session after an exception occurs)

异常发生后,会话处于无效状态,应立即释放。这就是您应该始终在事务中执行写入的原因之一。如果没有,您就不知道数据库的状态。因此,我建议:

  • 您不会显式刷新数据,并且始终坚持数据访问(读取和写入)是在事务内部完成的
  • 如果这不是一个选项,我会鼓励您找到异常的根本原因-听起来您有一个实体映射了一个从未设置过的分配id-并修复它
  • 如果这不是选项,则在发生异常时处置会话

  • 希望这能有所帮助。

    不刷新会话会产生什么影响?如果上一个会话没有刷新,下一个“Save”调用会发生什么?
    null id in FoodOrder.Core.Entities.Articles entry (don't flush the Session after an exception occurs)
    
    public void CommitChanges()
            {
                if (NHibernateSessionManager.Instance.HasOpenTransactionOn(SessionFactoryConfigPath))
                {
                    NHibernateSessionManager.Instance.CommitTransactionOn(SessionFactoryConfigPath);
                }
                else
                {
                    try
                    {
                        // If there's no transaction, just flush the changes
                        NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath).Flush();
                    }
                    finally
                    {
                        NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath).Close();
                    }
                }
            }