处理NHibernate Load失败

时间:2011-05-06 09:43:51

标签: nhibernate exception load

我有以下方法。

    public Foo GetById(int id)
    {
        ISession session = GetCurrentSession();
        try
        {
            return session.Load<Foo>(id);
        }
        catch(NHibernate.ObjectNotFoundException onfe)
        {
            throw(onfe);
        }
    }

不幸的是,onfe永远不会被抛出。我想处理我得到的情况 支持代理,因为数据库中不存在足够的行。

2 个答案:

答案 0 :(得分:3)

我建议您编写自己的ObjectNotFoundException并将方法重写为:

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));
    }
}

您的方法有两个问题:

  1. 您应该使用Get按键加载实体。
  2. 您的异常处理是包装原始异常并无缘无故重新投掷。

答案 1 :(得分:2)

如果允许实体延迟加载,则Load方法返回未初始化的代理。一旦代理即将被初始化,就会抛出ObjectNotFoundException。

当您不确定所请求的实体是否存在时,应优先选择Get方法。

请参阅: Nhibernate error: NO row with given identifier found errorhttps://sites.google.com/a/thedevinfo.com/thedevinfo/Home/or-persistence/hibernate/hibernate-faq等等......