NHibernate, ISession per presenter, multiple presenters open

狂风中的少年 提交于 2020-01-04 07:58:30

问题


How would you solve the following situation: the app is MVP based (WinForms) and at the same time I can have multiple presenters showing. Each presenter has a session attached, and open during the lifetime of the presenter.

If I load an entity in one presenter and pass it through to another to show it, and if that entity has some collection to it, I get "Illegal attempt to associate a collection with two open sessions".

Now, am I doing something wrong with my architecture? I don't see a problem with mutiple sessions open (connections are of course not open all the time).

Any opinions are much appreciated!


回答1:


When you retrieve data from a database using NHibernate, the returned entity objects get associated to the ISession instance that materialized them. All subsequent operations involving the database on any of those objects must be performed through the same ISession instance. This includes fetching associated collections of entities via lazy loading.

One way to solve this problem is making sure that any collections associated to the entity object are already populated before passing it to another session. There are a couple of ways of achieving this:

  1. You could load the collections after the entity object has been retrieved by simply accessing their relative properties on the entity object, thus triggering lazy loading.
  2. You could retrieve the entity object together with its associated collections through eager loading.

Note that in both cases you should completely detach the entity object from its session before passing it to another one by calling the ISession.Evict method.




回答2:


Denis, I have been fighting exactly the same problem in an MVP Winforms application and the best way we could find to solve the problem reliably was to move to a "Persistent conversations" model rather than "Session Per Presenter".

This previous questions contains many of the links you will need

Example of nhibernate winform application



来源:https://stackoverflow.com/questions/6518674/nhibernate-isession-per-presenter-multiple-presenters-open

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!