我有以下看似简单的场景,但我对 NHibernate 仍然很陌生。
当尝试在我的控制器上加载以下模型以进行编辑操作时:
控制器的编辑操作:
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);
}
Model:
public class SomeModel
{
public virtual string Content { get; set; }
public virtual IList<SomeOtherModel> SomeOtherModel { get; set; }
}
我收到以下错误:
- 未能延迟初始化角色集合:SomeOtherModel,没有会话或会话被关闭
我在这里缺少什么?
问题是您在模型中创建并关闭了会话GetById
方法。 (using 语句关闭会话)会话在整个业务事务期间必须可用。
有多种方法可以实现这一目标。您可以将 NHibernate 配置为使用会话工厂 GetCurrentSession 方法。看这个在 nhibernate.info 上 http://nhibernate.info/doc/nhibernate-reference/architecture.html#architecture-current-session or 这篇关于代码项目的文章 http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx.
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();
}
无论您如何实现,会话和事务都应该与业务事务(或系统功能)一样长。除非你不能依赖事务隔离也不能回滚整个事情。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)