我正在尝试修复某些遗留代码中的错误。代码试图从数据库中删除一个对象(一行)。但是,Session有时不包含该对象并抛出异常。我添加了测试以查看Session是否包含对象,然后尝试各种方法将对象放入Session中,但到目前为止还没有成功。你能建议我还能尝试什么吗?
这段代码实现了nHibernate Session非常糟糕,因为它不遵循工作单元的道德规范。应用程序在启动时会创建一个会话,并在应用程序的整个生命周期中使用该会话。我无能为力(完全重写除外,在这种情况下我会放弃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;
}
}
答案 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();
}