Search code examples
c#nhibernatefluent-nhibernate

Nhibernate GetById returns ObjectNotFoundException insetad of null


I am using fluent Nhibernate. This code Loads an instance of type T from the DB based on its ID.

public T GetById(IdT id, bool shouldLock)
    {
        T entity;

        if (shouldLock)
        {
            entity = (T) NHibernateSession.Load(persitentType, id, LockMode.Upgrade);
        }
        else
        {
            entity = (T) NHibernateSession.Load(persitentType, id);
        }

        return entity;
    }

But I have big problem. When I call property on it I get ObjectNotFoundException instead of null.

How can I make that entity be nullable and not return the Exception?


Solution

  • I would use Get instead of Load. Get will return null, instead of an exception.