Many-to-One
家长包含物业孩子,孩子可以从几个家长联系起来。
class Parent
{
public virtual MyItem Child { get; set; }
}
<class name="Parent">
<many-to-one name="Child" column="MyItemId" />
</class>
Many-to-Many with a join table
家长包含的子集,孩子们可以从几个家长联系起来。
class Parent
{
public virtual IList<MyItem> Children { get; set; }
}
<class name="Parent">
<bag name="Children" table="parent_myitem">
<key column="parentid" />
<many-to-many class="MyItem" column="MyItemId" />
<bag>
</class>
Criteria Querying
// find Parent with child named "foo".
DetachedCriteria.For<Parent>()
.CreateAlias("Child", "c")
.Add(Restrictions.Eq("c.Name", "foo"));
// find Parent with particular child
DetachedCriteria.For<Parent>()
.Add(Restrictions.Eq("Child", child));
// find Parent with one of children named "foo".
DetachedCriteria.For<Parent>()
.CreateAlias("Children", "c")
.Add(Restrictions.Eq("c.Name", "foo"));
// find a "page" of children for a parent
DetachedCriteria.For<Parent>()
.Add(Restrictions.Eq("Id", parent.Id))
.CreateAlias("Children", "c")
.SetFirstResult(1041)
.SetMaxResults(20)
.GetExecutableCriteria(session)
.List<MyItem>();
这最后的查询可能会或可能不会被更有效地利用只是延迟加载上首次访问整个儿集合,然后索引到它后来的“做页面”。这取决于您的数据和使用情况。
除非我先知道孩子的收藏会是巨大的,否则我会首先进入懒惰的负载路线。如果时间和profiling显示严重缓慢,那么我会切换到标准方法。
伟大的问题。很棒,正是我想问的。 – Slavo