views:

55

answers:

1

Hi all,

I wonder if there is a smooth way of keeping track of changed entities using NHibernate.

Session.IsDirty() is a fine way of knowing there are changes, but not which. Up to now, I've logged my changes in a List to be able to specify them later on. Eventually I would loop over that list and call Session.Save() on each of them and remove the item from the list.

Is there any way I can get around this?

Thanks a lot in advance

Sebi

A: 

It sounds like you are trying to work around the problem that your session lifetime is wrong. A session is designed to be used for a single unit of work. Instead of clearing the session in this way to carry on using it, you should be flushing it and starting again with a new one. If you are using this to speed the application up due to caching, I suggest you look at second-level caching in NHibernate, which operates at the SessionFactory rather than Session level.

If you have a long-running editing process, with a large batched save at the end, then in my view you should be working with the objects disconnected. So you use one session to load the objects, and any of their related objects, edit with them outside the context of a session, then at the end of the process, reattach these objects to a new session using SaveOrUpdate and then flush that session. This sort of approach works best if you are using offline otimistic locking for your concurrency approach, using for example a SQL Server timestamp column or the Oracle ORA_SCN virtual column as your version. If an object has changed underneath you, then the update will fail with a StaleObjectStateException.

But YMMV, and I'd need to know more about your application to say anything more specific than this.

David M
Help me get this straight...My session lifetime ranges from reading objects from DB over modifying some to posting those changes back. Then, a new session starts.How would you propse I do this? Do you, by any chance, have a best practice example?Thanks a lot
Sebastian Edelmeier
I've edited the answer a little. The more you can tell me, the more I can tell you... :)
David M
I'm with you there. Using separate sessions sounds like a good thing to do. I will look into this. Anyway, for my original issue that would mean I'd still have to employ a manual approach of changetracking, right?
Sebastian Edelmeier
Yes, I think it would.
David M