NHibernate Pitfalls: Loading Foreign Key Properties

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

When saving a new entity that has references to other entities (one to one, many to one), one has two options for setting their values:

Load each of these references by calling ISession.Get and passing the foreign key;

Load a proxy instead, by calling ISession.Load with the foreign key.

So, what is the difference? Well, ISession.Get goes to the database and tries to retrieve the record with the given key, returning null if no record is found. ISession.Load, on the other hand, just returns a proxy to that record, without going to the database. This turns out to be a better option, because we really don’t need to retrieve the record – and all of its non-lazy properties and collections -, we just need its key.