senzacionale
senzacionale

Reputation: 20906

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?

Upvotes: 6

Views: 3628

Answers (3)

anivas
anivas

Reputation: 6547

Load will never return null. It will always return an entity or throw an exception. If you want that behaviour use Get. More info on this Difference between Get and Load

Upvotes: 4

Kevin Stricker
Kevin Stricker

Reputation: 17388

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

Upvotes: 12

Chris Marisic
Chris Marisic

Reputation: 33098

I think you're mistaken in what Load does. This create an NHibernate proxy object for you by ID without actually querying the database.

When you invoke a property it will query the database, if you supplied a bad id there is no underlying object hence the exception.

The normal situtations you will use this is for is say you have a State object and the user selected PA in a drop down. Instead of having to query the database for the State object since you already have the key PA you can call Load and then pass that state object into a different object to have the correct relationship of Object X to State PA.

The method you want to be using for general get object or get null if key does not exist is just Session.Get<T>(object ID)

Upvotes: 10

Related Questions