假设我运行以下代码:
var placementCriteria = DetachedCriteria.For<ResidentialPlacementClientService>();
placementCriteria.Add(Restrictions.Le("StartDate", effectiveDate));
placementCriteria.Add(Restrictions.Ge("EndDate", effectiveDate));
placementCriteria.SetFetchMode("CaseClient.CaseFile", FetchMode.Eager);
placementCriteria.SetFetchMode("CaseClient.Incomes", FetchMode.Eager);
placementCriteria.SetFetchMode("CaseClient.ClientProfile", FetchMode.Eager);
placementCriteria.SetFetchMode("CaseClient.ClientProfile.Person", FetchMode.Eager);
placementCriteria.SetFetchMode("VendorService", FetchMode.Eager);
placementCriteria.SetFetchMode("VendorService.Vendor", FetchMode.Eager);
using (var session = OpenSession())
{
using (var tx = session.BeginTransaction())
{
residentialPlacements = placementCriteria.GetExecutableCriteria(session).List<ResidentialPlacementClientService>();
}
}
我的“收入”属性已正确填充。
现在,当我添加收入标准时,不再急切地获取该属性。
var placementCriteria = DetachedCriteria.For<ResidentialPlacementClientService>();
placementCriteria.Add(Restrictions.Le("StartDate", effectiveDate));
placementCriteria.Add(Restrictions.Ge("EndDate", effectiveDate));
placementCriteria.SetFetchMode("CaseClient.CaseFile", FetchMode.Eager);
placementCriteria.SetFetchMode("CaseClient.Incomes", FetchMode.Eager);
placementCriteria.SetFetchMode("CaseClient.ClientProfile", FetchMode.Eager);
placementCriteria.SetFetchMode("CaseClient.ClientProfile.Person", FetchMode.Eager);
placementCriteria.SetFetchMode("VendorService", FetchMode.Eager);
placementCriteria.SetFetchMode("VendorService.Vendor", FetchMode.Eager);
var caseClientCriteria = placementCriteria.CreateCriteria("CaseClient", JoinType.InnerJoin);
var incomesCriteria = caseClientCriteria.CreateCriteria("Incomes", JoinType.InnerJoin);
incomesCriteria.Add(Restrictions.Le("StartDate", effectiveDate));
incomesCriteria.Add(Restrictions.Or(Restrictions.Ge("EndDate", effectiveDate),
Restrictions.IsNull("EndDate")));
incomesCriteria.Add(Restrictions.Eq("IncomeType", incomeType));
using (var session = OpenSession())
{
using (var tx = session.BeginTransaction())
{
residentialPlacements = placementCriteria.GetExecutableCriteria(session).List<ResidentialPlacementClientService>();
}
}
为什么NHibernate这样做?如何更改我的查询/条件以便急切地获取属性?
感谢。
答案 0 :(得分:3)
如果您在关联上有过滤器,那么NH无法确保返回该关联的所有实体以初始化关联集合。您可以为id发出Select,然后急切地获取具有关联的实体
...
placementCriteria.SetProjection(Projections.Id());
residentialPlacements = session.CreateCriteria<ResidentialPlacementClientService>()
.Add(Subqueries.In("Id", placementCriteria))
.SetFetchMode("CaseClient.CaseFile", FetchMode.Eager);
.SetFetchMode("CaseClient.Incomes", FetchMode.Eager);
.SetFetchMode("CaseClient.ClientProfile", FetchMode.Eager);
.SetFetchMode("CaseClient.ClientProfile.Person", FetchMode.Eager);
.SetFetchMode("VendorService", FetchMode.Eager);
.SetFetchMode("VendorService.Vendor", FetchMode.Eager);
.List<ResidentialPlacementClientService>();