NHibernate -failed to lazily initialize a collection of role

后端 未结 3 1280
-上瘾入骨i
-上瘾入骨i 2021-02-07 03:04

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

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

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 03:34

    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.

    There are several ways to achieve this. You can configure NHibernate to use the session factories GetCurrentSession method. See this on nhibernate.info 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(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.

提交回复
热议问题