Nhibernate GetById returns ObjectNotFoundException insetad with a null value

I use free Nhibernate. This code Loads an instance of type T from the database based on its identifier.

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 a big problem. When I call a property on it, I get an ObjectNotFoundException instead of null .

How can I make this object be NULL and not return an Exception?

+6
c # nhibernate fluent-nhibernate
source share
3 answers

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

+12
source share

I think you're wrong about what Load does. This creates an NHibernate proxy object for you by ID without actually querying the database.

When you call a property, it will query the database, if you provided an invalid identifier, there is no underlying object, so an exception.

The usual situtations for which you will use this, for example, is that you have a State object, and the user selects PA from the drop-down list. Instead of querying the database for the State object, since you already have the PA key, you can call Load , and then pass that state object to another object to have the correct relationship between the X object and State PA.

The method you want to use for a common get object or get null if the key does not exist is just Session.Get<T>(object ID)

+9
source share

Load will never return null. It always returns an object or throws an exception. If you want this behavior to use Get . Additional Information About This Difference Between Get and Load

+4
source share

All Articles