我有以下看似简单的场景,但是对于NHibernate来说我还是很新。
尝试为 Controller 上的“编辑”操作加载以下模型时:
Controller 的编辑 Action :
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; }
}
我收到以下错误:
-无法延迟初始化角色集合:SomeOtherModel,没有 session 或 session 被关闭
我在这里想念什么?
最佳答案
问题是您在模型GetById
方法中创建并关闭了 session 。 (using语句关闭 session )在整个业务交易期间 session 必须可用。
有几种方法可以实现此目的。您可以将NHibernate配置为使用 session 工厂的GetCurrentSession方法。参见this on nhibernate.info或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);
}
我不使用这个。我编写了自己的交易服务,该服务可以执行以下操作:
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();
}
无论您实现它如何, session 和事务都应与业务事务(或系统功能)一样有效。除非您不能依赖事务隔离,也不能回滚整个过程。
关于asp.net-mvc - NHibernate-无法延迟初始化角色集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1893611/