Handle NHibernate Load fail
I have开发者_Python百科 the following method.
public Foo GetById(int id)
{
ISession session = GetCurrentSession();
try
{
return session.Load<Foo>(id);
}
catch(NHibernate.ObjectNotFoundException onfe)
{
throw(onfe);
}
}
Unfortunately, onfe is never thrown. I want to handle the case that I only get back a proxy because no adequate row exists in database.
I suggest you write your own ObjectNotFoundException and rewrite the method as:
public Foo GetById(int id)
{
Foo foo;
ISession session = GetCurrentSession();
foo = session.Get<Foo>(id);
if (foo == null)
{
throw new ObjectNotFoundException(string.Format("Foo with id '{0}' not found.", id));
}
}
There are two problems with your method as written:
- You should use
Get
to load an entity by its key. - Your exception handling is wrapping the original exception and re-throwing for no reason.
If an entity is allowed to be lazy-loaded then Load method returns uninitialized proxy. The ObjectNotFoundException is thrown as soon as the proxy is about to be initialized.
Get method should be prefered when you are not sure that a requested entity exists.
See: Nhibernate error: NO row with given identifier found error , https://sites.google.com/a/thedevinfo.com/thedevinfo/Home/or-persistence/hibernate/hibernate-faq, etc...
精彩评论