例子:
public class ParentObj
{
public virtual int Id { get; set; }
public virtual IList<ChildObj> ChildCollection { get; set; } //Lazy loaded
}
在一个页面(网络)上获取父对象的一些方法
ParentObj parentObj;
using (var session = GetSesion())
using (var tx = session.BeginTransaction())
{
parentObj = session.Get<ParentObj>(1);
//Don't want to call NHibernateUtil.Initialize() here
//because ChildCollection is not needed for the current operation
}
将 parentObj 转移到另一个页面,现在我需要访问 ChildCollection
var parentOjb = GetParentOjbFromPreviousPage();
using (var session = GetSesion())
using (var tx = session.BeginTransaction())
{
parentOjb = session.Merge(parentObj);
NHibernateUtil.Initialize(parentObj.ChildCollection); //exception thrown here
}
错误消息:集合未与任何会话关联
我究竟做错了什么?在这种情况下初始化 ChildCollection 的唯一方法是再次调用 Get() 吗?