子对象上的 CreateCriteria 时出现 lazyinitializationexception

lazyinitializationexception when CreateCriteria on child object

我真的不明白这种情况,我有两个对象 Doctor 和 Appointment,这 2 个 table 是通过一个 Id 映射 table:

Doctor.hbm.xml:

<bag name="Appointments" table="AppointmentDoctor" lazy="true">
  <key>
    <column name="DoctorId"/>
  </key>
  <many-to-many class="Appointment">
    <column name="AppointmentId"/>
  </many-to-many>
</bag>

当我执行此请求时,它工作正常:

            var criteria = session.CreateCriteria(typeof(Doctor));
            criteria.SetFetchMode("Appointments", FetchMode.Join);

添加SetFetchMode的事实returns约会正确。

但是一旦我创建了这样的子查询:

            var criteria = session.CreateCriteria(typeof(Doctor));
            criteria.SetFetchMode("Appointments", FetchMode.Join);
            
            //New sub query
            var appointmentsCriteria = criteria.CreateCriteria("Appointments");
            appointmentsCriteria.Add(Restrictions.Eq("AppointmentState", AppointmentState.Cancelled));

Appointment 的获取不再完成,稍后我得到一个 lazyinitializationexception。

知道为什么会这样吗?

criteria.CreateCriteria("Appointments") 覆盖您使用 criteria.SetFetchMode("Appointments", FetchMode.Join); 请求的行为。默认情况下不获取内部加入的集合条件。所以你必须使用左连接:

//Collection criteria must be left joined to be fetched
var appointmentsCriteria = criteria.CreateCriteria("Appointments", JoinType.LeftJoin);
            

或者,如果您使用的是 NHibernate 5.2+,则可以使用 SelectMode.Fetch 来获取内部连接的集合:

var appointmentsCriteria = criteria.CreateCriteria("Appointments")
                               .Fetch(SelectMode.Fetch, string.Empty);

有关 SelectMode 的更多信息,请参阅 here