从一个会话中检索对象并在另一个会话中更新nHibernate

时间:2018-01-06 11:45:51

标签: c# nhibernate

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

  

该操作对于征兵的当前状态无效。

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

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

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

每次打开新的会话是一种好方法,还是应该在 SessionFactory 中使用 Singleton模式

1 个答案:

答案 0 :(得分:1)

在使用其他{更新customer之前从ISession分离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);

ISession

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

修改(针对您的更新)

  

每次打开一个新会话是一个好方法还是我应该在SessionFactory中使用Singleton模式?

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

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

您可以选择在请求级别上移动您的UoW(即每个请求https://management.azure.com/subscriptions/{subscriptionId}/resources?$filter=resourceType eq 'Microsoft.Compute/virtualmachines'&$top=10&api-version={apiVersion} ),您可以利用ORM功能获益;但同样还有其他与之相关的问题。请参阅以下内容:https://stackoverflow.com/a/48092471/5779732
Should I transform Entity (Persistent) objects to DTO objects?

相关问题