I have a generic methode for load the entity. I need to check result value for null value.
public TEntity LoadById(long id)
{
TEntity result = SessionInstance.Load<TEntity>(id);
if (result != null) //This condition is always true
if (result.Id == 0 ) //Throws ObjectNotFoundException
throw new Exception("Ex Text");
return result;
}
But my condition ( if (result != null) ) is always true and next line result.Propagate() is throw ObjectNotFoundException exception by this message : No row with the given identifier exists[RCISP.Domain.Entities.Person#1000]
Because result entity is a proxy. How can I check a condition for null value in a proxy?
Use NHibernate's ISession.Get instead of ISession.Load. Load throws an exception if the requested item does not exist, but it might also return a proxy that is later used to load the object from the database - and will only then throw if the item does not exist. That's what is happening to you.
Get on the other side returns null if the item does not exist in database. Exactly what you want.
More on that topic here.
Daniel's initial answer is correct. According to Ayende's blog, Load should only be used when you know that the item exists in the database.
Load will never return null. It will always return an entity or throw an exception. Because that is the contract that we have we it, it is permissible for Load to not hit the database when you call it, it is free to return a proxy instead.
Why is this useful? Well, if you know that the value exist in the database, and you don’t want to pay the extra select to have that, but you want to get that value so we can add that reference to an object, you can use Load to do so
In your example, the ObjectNotFoundException can only occur when the item does not exist in the database. If you can't guarantee that the item is present, you need to use Get not Load.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With