Load vs. Get in NHibernate

I really like the lazy-loading feature of NHibernate, because it can dramatically reduced unneeded traffic to your database.

But I had a hard time figuring out, why I could not distinguish whether an object exists in the database or not. Because of the way lazy-loading works, you always get an object returned by the load method. Usually this will be a proxy object. If you try to access a property of an non-existing entity (on the proxy), you well get an exception, but I would rather know this a time ahead.

Well, this is where the get method comes into play. This methode retrieves the values of the properties of an entity directly, instead of lazy-loading these values by using a proxy-object like the load method does.


  1. Well, an example is quite simple. This example will load an entity using the Load method:

    var nonExistingPizza = _session.Load(42);
    if (nonExistingPizza != null)
    var foo = nonExistingPizza.Name;

    If you load an entity by id which does not exist line 1 will work, but line 3 will throw an exception. The condition in line 2 will be true, because the variable “nonExistingPizza” is pointing to a proxy-class and thus not null.

    var nonExistingPizza = _session.Get(42);
    if (nonExistingPizza != null)
    var foo = nonExistingPizza.Name;

    If you use the Get method instead, you will get a null object if the entity does not exists, and thus line 3 will not be executed.

    I hope this helps.

Leave a Comment.