开发者

NHibernate, ISession per presenter, multiple presenters open

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开发者_Python百科 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!


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜