c# - 从一个 session 中检索对象并在另一个 session 中更新 nHibernate

标签 c# nhibernate

我需要更新客户详细信息。为此,我必须从存储库的另一个 session 中检索实体,并在 服务 中更新该实体。当我这样做时,我收到一条错误消息:

The operation is not valid for the current state of the enlistment.

但是,如果我更新了实体而不从数据库中检索它,一切正常。

这就是我在服务中尝试更新的方式。

 Customer customer = customerService.getById(customer_payment.customer_id);
 customer.deductBalance(customer_payment.discount_received);
 customerService.updateCustomerDetails(customer);

这是我更新实体的存储库:

using (ISession session = SessionFactory.OpenSession)
  {
    using(ITransaction t = session.BeginTransaction())
        {
          session.SaveOrUpdate(customer);
           t.Commit();
        }
   }

这是我的函数,它返回给定 ID 的实体:

客户客户;

using (ISession session = SessionFactory.OpenSession)
  {
   customer = session.Get<Customer>(customer_id);
  }
 return customer;

我该如何解决这个问题?提前致谢。

编辑 1:这是我的 OpenSession 所做的:

Configuration configuration = new Configuration().Configure("hibernate.cfg.xml");
Assembly assembly = Assembly.GetCallingAssembly();
configuration.AddAssembly(assembly);
iSessionFactory = configuration.BuildSessionFactory();
CurrentSessionContext.Bind(iSessionFactory.OpenSession());
return iSessionFactory.OpenSession();

每次都打开一个新的 session 是一个好方法还是我应该在SessionFactory中使用单例模式

最佳答案

从第一个 ISession 中分离 customer,然后再更新它。您必须在存储库上公开 Evict 方法,或者必须在存储库外部公开 ISession

Customer customer = customerService.getById(customer_payment.customer_id);

customerService.Evict(customer);
//OR
customerRepository.Evict(customer);
//OR
customerService.Session.Evict(customer);
//OR something similar...

customer.deductBalance(customer_payment.discount_received);
customerService.updateCustomerDetails(customer);

引用以下内容:
https://ayende.com/blog/4282/nhibernate-cross-session-operations
What does NHibernate Session.Evict do?
Can I detach an object from an NHibernate session?

编辑(为您的更新)

Is it a good approach to open a new session everytime or should I use Singleton pattern in SessionFactory?

这实际上是基于意见的问题;但建议您的 ISession 应该是短暂的。

也就是说,您可以为每个数据库操作创建新 session 。但是通过这样做,您会错过许多 ORM 功能,例如 session 级缓存、延迟加载、更改跟踪 (UoW) 等。

您可以选择将 UoW 移动到请求级别(即每个请求的 ISession),您可以利用 ORM 功能的好处;但同样还有其他与之相关的问题。引用以下:https://stackoverflow.com/a/48092471/5779732
Should I transform Entity (Persistent) objects to DTO objects?

关于c# - 从一个 session 中检索对象并在另一个 session 中更新 nHibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48127026/

相关文章:

c# - 如何从以特定方式格式化的字符串之间访问特定值c#

c# - 当我只能在 C# 中使用 float 或 double 时,为什么我应该使用整数?

nhibernate - 如何在 nhibernate 中使用 PK 删除对象?

nhibernate - 如何对同一列使用 NHibernate DiscriminateSubClassesOnColumn 和 References

c# - 关闭上传流的 FtpWebRequest 卡在大文件上

C# MySQL Order By 返回 -1

c# - Unity Networking-UNet 中的附加场景加载

.net - NHibernate 中的延迟初始化

c# - 创建代理实例失败,出现 COMException(IIS、Windows Server 2012、NHibernate)

.net - 休眠环境 : auditing an entity already in production