NHibernate的-failed懒洋洋地初始化角色的集合 [英] NHibernate -failed to lazily initialize a collection of role

查看:514
本文介绍了NHibernate的-failed懒洋洋地初始化角色的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几个看似简单的场景,但我仍然pretty新NHibernate的。

I have the following seemingly simple scenario, however I'm still pretty new to NHibernate.

当试图加载下面的模型在我的控制器上的Edit操作:

When trying to load the following model for an Edit action on my Controller:

控制器的编辑操作:

public ActionResult Edit(Guid id)
{
    return View(_repository.GetById(id));
}

存储库:

public SomeModel GetById(Guid id)
{
    using (ISession session = NHibernateSessionManager.Instance.GetSession())
        return session.Get<SomeModel >(id);
}

型号:

public class SomeModel
{
    public virtual string Content { get; set; }
    public virtual IList<SomeOtherModel> SomeOtherModel { get; set; }
}

我收到以下错误:

I get the following error:

-failed懒洋洋地初始化角色的集合:SomeOtherModel,没有会话或会话关闭

-failed to lazily initialize a collection of role: SomeOtherModel, no session or session was closed

我是什么在这里失踪?

推荐答案

的问题是,您创建并也在你的模型 GetById 方法关闭会话。 (using语句关闭会话)的全业务交易在会议期间必须是可用的。

The problem is that you create and also close the session in you models GetById method. (the using statement closes the session) The session must be available during the whole business transaction.

有几种方法来实现这一目标。您可以配置N​​Hibernate的使用的会话工厂的getCurrentSession方法。请参见这个职位上NHForge 或的this~~MD~~aux张贴在code项目

There are several ways to achieve this. You can configure NHibernate to use the session factories GetCurrentSession method. See this post on NHForge or this post on Code Project.

public SomeModel GetById(Guid id)
{
    // no using keyword here, take the session from the manager which
    // manages it as configured
    ISession session = NHibernateSessionManager.Instance.GetSession();
    return session.Get<SomeModel >(id);
}

我不使用这个。我写我自己的交易服务,它允许以下内容:

I don't use this. I wrote my own transaction service which allows the following:

using (TransactionService.CreateTransactionScope())
{
  // same session is used by any repository
  var entity = xyRepository.Get(id);

  // session still there and allows lazy loading
  entity.Roles.Add(new Role());

  // all changes made in memory a flushed to the db
  TransactionService.Commit();
}

不过你实现它,会话和交易应生活,只要商业交易(或系统功能)。除非你不能依靠事务隔离,也没有回滚整个事情。

However you implement it, sessions and transactions should live as long as a business transaction (or system function). Unless you can't rely on transaction isolation nor rollback the whole thing.

这篇关于NHibernate的-failed懒洋洋地初始化角色的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆