处理 NHibernate 加载失败
我有以下方法。
public Foo GetById(int id)
{
ISession session = GetCurrentSession();
try
{
return session.Load<Foo>(id);
}
catch(NHibernate.ObjectNotFoundException onfe)
{
throw(onfe);
}
}
不幸的是,onfe 永远不会被抛出。我想处理我只得到的案件 返回代理,因为数据库中不存在足够的行。
I have 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议您编写自己的 ObjectNotFoundException 并将该方法重写为:
您所编写的方法有两个问题:
Get
通过实体的键加载实体。I suggest you write your own ObjectNotFoundException and rewrite the method as:
There are two problems with your method as written:
Get
to load an entity by its key.如果允许实体延迟加载,则 Load 方法返回未初始化的代理。一旦代理即将初始化,就会抛出 ObjectNotFoundException。
当您不确定所请求的实体是否存在时,应首选 Get 方法。
看:
Nhibernate 错误:没有找到具有给定标识符的行错误
,
https://sites.google。 com/a/thedevinfo.com/thedevinfo/Home/or-persistence/hibernate/hibernate-faq 等...
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...