我有一個包含子實體列表的父項實體。當使用NHibernate從SQL中檢索給定的父級子項時,如果沒有子項或者子項的日期與where條件匹配,則它工作正常。NHibernate - 使用僅適用於子項的條件檢索父項/子項
如果有子項與where子句不匹配,則父項爲空。我想讓父母用空的兒童列表進行初始化。
有關如何修改下面的代碼以實現此目的的任何想法?
實體:
public class Parent
{
public int ParentId;
public IList<Child> Children { get; set; }
public Parent()
{
Children = new List<Child>();
}
}
public class Child
{
public int ChildId;
public DateTime ChildDate;
public Parent Parent { get; set; }
}
庫:
IList<Parent> foundParents = new List<Parent>();
var criteria1 = DetachedCriteria.For<Parent>()
.Add(Restrictions.Eq("ParentId", parentId))
.CreateCriteria("Children", JoinType.LeftOuterJoin)
.Add(Restrictions.Or(
Restrictions.IsNull("ChildDate"), // no children at all
Restrictions.And(
Restrictions.Ge("ChildDate", startDate),
Restrictions.Le("ChildDate", endDate)
)
));
foundParents = Session
.CreateMultiCriteria()
.Add<Parent>(criteria1)
.SetResultTransformer(new DistinctRootEntityResultTransformer())
.List()[0] as List<Parent>;
如果我這個寫SQL,我會把在左邊的日期比較加入,而不是在哪裏條款。我無法弄清楚如何用NHibernate做到這一點。