Today have come across a strange error with the inserting of transient objects. Which leads me to question whether I understand how it works (hence this post :-) Am using sessions in separate generic DBAccess layer implementation. which is not always aware of which object is new (transient) and which one is loaded (persistent). To make sure that I have the latest version of an object before starting edit I wanted to use the Lock(o, LockMode.Read) call, but since it fails for transient objects I first call SaveOrUpdate(o) just to be sure.
Code:
With GetCurrentSession()
.SaveOrUpdate(o) 'Just to prevent errors on lock call
.Lock(o, LockMode.Read) ' making sure I have latest version (will cause exception if I don't)
End With
Now comes the issue, when then making changes to the object there is no problem at all until I try to save the newly created object. This runs the following code, so in fact it just calls SaveOrUpdate on my associated new object again and then commits the session. This immediately raises an exception since the generated
SQL INSERT statement does not contain any of the changes I made to the object since the original SaveOrUpdate call was made. Instead, it
tries to insert NULL values (whereas the actual properties have all got valid values)
Code:
With GetCurrentSession()
Using .BeginTransaction
.SaveOrUpdate(o)
.Transaction.Commit()
End Using
End With
Can someone explain why this behaviour is as expected? (or is this a bug?) I expected that after the first saveorupdate NHibernate automatically monitors the changes made to the properties.