Wednesday, December 19, 2012

NHibernate Get vs Load behavior in whether returning the proxy or not

When returning an entity by using Get or Load, NHibernate first tries to return it from the session cache.
If it’s not there, then Get and Load will return the entity in a different way.
When calling Get, NHibernate will perform a roundtrip to database and return the non-proxy entity object or null in case the record does not exist:
var user = session.Get<User>(122);
For Load, NHibernate will return a proxy of the entity object or throw an exception if the record does not exist:
var user = session.Load<User>(122);
Suppose we have the following calls:
var a = session.Load<Assignment>(1);
var b = session.Get<Assignment>(1);
Note that in the 2nd case, b is a proxy and not the entity because the entity proxy exists in the session cache due to the Load call.
var a = session.Get<Assignment>(1);
var b = session.Load<Assignment>(1);
In this case b is a non-proxy entity object, due to the Get call.

No comments: