Question

I'm implemented the unit of work like this tutorial explained: http://www.codeproject.com/Articles/543810/Dependency-Injection-and-Unit-Of-Work-using-Castle

Though now I encounter a strange problem.

  • I load within a unit of work (in the transaction) an entity from the database
  • I update a property of that entity
  • I call not the save method on my repository
  • The transaction is committed

In this scenario, I would expect that the updated property is not persisted to the database. But it is. So an entity loaded in my session is tracked and committed to the database without calling save. What is causing this? And is there a way to tell Nhibernate not to update those entities if the save is not called?

I realize I can work around this to update only a property when I need to update. The only risk is by accident updating the property by mistake and it is then very hard to find this problem. (and for example someone new, not knowing this could easily make a mistake)

Was it helpful?

Solution

The explanation requires understanding the difference between a transient and a persistent entity. A transient entity is a new entity and it is made persistent by calling Save(). An entity that has been retrieved using NHibernate is already persistent and any changes made to it will be automatically saved when the session is flushed. NHibernate's goal is to make the database consistent with the domain model when the session ends.

See chapter 9 in the documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top