【问题标题】:Attach an object to a session将对象附加到会话
【发布时间】:2018-01-08 12:16:23
【问题描述】:

我正在尝试修复一些遗留代码中的错误。该代码试图从数据库中删除一个对象(一行)。但是,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;
    }
}

【问题讨论】:

  • 您可以尝试以其他方式删除:stackoverflow.com/a/25762358/1162077
  • 感谢您的建议。这似乎是一种改进。它删除该行并引发异常。不过,你无法判断,我的代码中有一些特殊的东西。

标签: c# session nhibernate


【解决方案1】:

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

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

【讨论】:

  • Get 命中数据库或会话缓存以检索实体数据。如果实体存在,它将被返回。否则将返回null
猜你喜欢
  • 2014-08-09
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 2021-07-14
  • 2012-12-02
  • 1970-01-01
相关资源
最近更新 更多