asp.net-mvc - NHibernate-无法延迟初始化角色集合

标签 asp.net-mvc nhibernate fluent-nhibernate

我有以下看似简单的场景,但是对于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.infothis 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/

相关文章:

asp.net-mvc - 如何从 Razor View 访问 My.Resources

c# - MVC 上的依赖注入(inject)问题

nhibernate - 使用 NHibernate 的时间数据

c# - 比较从 NHibernate 加载的对象时,== 是否保证有效?

fluent-nhibernate - Fluent 1.2 从 NH 3.0 升级到 3.1 时出现警告 -- ProxyFactoryFactory is obsolete, moved to

visual-studio - 为什么在运行我的应用程序时会遗漏一些引用?

asp.net-mvc - 使用 MVC Web 应用程序时,Nhibernate 的最佳缓存是什么?

c# - ASP.NET HttpContext.Current.Session 突然总是空的

nhibernate - 选择或选择列表 : I Want to include the entire entity

c# - 如何在 Fluent NHibernate 中映射 IDictionary<string, Entity>