Search code examples
c#nhibernatefluent-nhibernate

Are there occasions when NHibernate won't return a proxy object?


I'm learning Fluent NHibernate (and by extension, NHibernate generally). I'm using auto-mapping with some overrides, but I don't think that is important for the question (of course, if I'm wrong here I'll gladly update the question).

Given an ISession (and a few more assumed variables) I can return entities by their ID:

using (var session = SessionFactory.OpenSession())
{
    var user = session.Get<User>(userId);
}

My limited understanding was that NHibernate creates a proxy around the User mapped entity, yet when I test it (based on this):

Assert.That(user is INHibernateProxy, "Not a proxy.");

It appears as though my instance is not a proxy.

Are there occasions where proxies are not used? I'm hoping for the "missing piece" and praying this isn't the Friday afternoon brain-fail.


Solution

  • Generally proxies are for lazy loading. Whenever you're fetching entitles by Get etc., you're not getting proxies, but the real objects. NHibernate don't use proxies when not necessary.

    But if user has an Address, user.Address is INHibernateProxy will be true (unless lazy loading is turned off for this relationship).

    For more info about how and when NHibernate handles proxies, see this article.