问题
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:
- 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.
- 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