views:

39

answers:

3

I am using fluent nhibernate. This is 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 will be nullable and not return exception?

+7  A: 

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

mootinator
-1. Entity type is nullable, it is most likely a reference type.
Aliostad
Regardless, the solution to the problem is to use Get, rather than trying to lazy load...
mootinator
+1 this is the correct answer just lacking the explanation I gave with mine.
Chris Marisic
thx mootinator you save my day :)
senzacionale
+6  A: 

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)

Chris Marisic
+2  A: 

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

anivas