Clarification of NHibernate ‘Update’ – used to ‘Attach’

Some of the wording on the NHibernate Session functions can be a tad misleading, or hard to understand.  One is ‘Update’, Update in many ways should be called ‘Attach’!  So, let’s review what Update does:


This sounds like something you call to ‘save’ something right?  Actually it’s not.  The ‘save’ occurs on Save/Commit/Flush.  ie.

using var tran = new Transaction
  Order order = Session.GetById(…)
  order.Updated = true;
  Session.Update(order)     <— not needed

Update is actually for ‘tracking’ – not saving.  Let’s say you have an object that is detached from a session – by calling Update on that object will tell NHibernate to start tracking the object again.

ie let’s say we get Order from the HttpSession…

Order order = Session[“Order”] as Order;

So, in summary ‘Update’ is for re-associating an object back to the the NHibernate session.   Here is the catch as well – it is telling NHibernate that it is expecting it to be ‘saved’.  You can use Lock and define a LockMode to tell NHibernate that a ‘save’ might not be required.

In a test simulating a n-tier environment, I did detach (Evict) the object, then call ‘Update’ and ‘Lock’, it was able to save the object.  I plan on seeing how to work with optimistic concurrency.

What I find interesting is how badly Linq to Sql appears to handle this vs. NHibernate.  This is what I’m researching at the moment, so if anyone has advice in this area let me know.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s