2017-08-01 105 views
1

我试图修复一些遗留代码中的错误。代码试图从数据库中删除一个对象(一行)。然而,会话有时不包含对象并引发异常。我已经添加了测试,以查看Session是否包含对象,然后尝试各种方法将对象放入Session中,但目前尚未成功。你能建议我还能尝试什么?将对象附加到会话中

此代码实施nHibernate会话非常糟糕,因为它不遵循工作单位伦理。应用程序在启动时创建一个会话,并在应用程序的整个生命周期中使用该会话。我无能为力(除了完全重写,在这种情况下,我会放弃nHibernate)。

using (ITransaction transaction = this.Session.BeginTransaction()) 
{ 
    try 
    { 
     if (Session.Contains(object)) 
     { 
      Session.Delete(object); 
      transaction.Commit(); 
     } 
     else // new code, Session does not contain object 
     { 
      try 
      { 
       //Session.Close(); 
       //Session.Dispose(); 
       //Session.Disconnect(); 
       Session.Merge(object); 
       Session.Save(object); // this does something 
       Session.Lock(object, LockMode.Upgrade); // .Write in invalid mode 
       Session.Update(object); 
       using (ITransaction transaction2 = this.Session.BeginTransaction()) 
       { 
        // this code executes with no error but does not delete the row from the database 
        Session.Delete(object); 
        transaction2.Commit(); 
       } 
      } 
      catch (System.Exception exception) 
      { 
       string message2 = exception.ToString(); 
       MessageBox.Show(message2, "Delete() Try it again ", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 
     } 
} 
    catch (System.Exception exception) 
    { 
     if (transaction != null) 
     { 
      transaction.Rollback(); 
     } 
     throw exception; 
    } 
} 
+1

你可以尝试用不同的方式来删除:https://stackoverflow.com/a/25762358/1162077 –

+0

感谢您的建议。这似乎是一种改进。它删除行并引发异常。没办法,你可以告诉,但在我的代码中有一些特殊的东西。 –

回答

0

为什么不先从会话中获取对象?

using (ITransaction transaction = Session.BeginTransaction()) 
{ 
    var persisted = Session.Get<SomeType>(object.Id); //object will be loaded if not already in the session 
    Session.Delete(persisted); 
    transaction.Commit(); 
} 
+0

'Get'命中数据库或会话高速缓存以检索实体数据。如果实体存在,它将被返回。否则返回'null'。 –