当我有一个带有一对多子集合的实体对象,并且我需要查询一个特定的子对象时,是否有一个我还没有想出的功能或一些聪明的模式来避免 NHibernate 获取整个儿童收藏?
例子:
class Parent
{
public virtual int Id { get; proteced set; } // generated PK
public virtual IEnumerable<Child> Children { get; proteced set; }
}
class Child
{
public virtual int Id { get; protected set; } // generated PK
public virtual string Name { get; protected set; }
public virtual Parent Parent { get; protected set; }
}
// mapped with Fluent
class Service
{
private readonly ISessionFactory sessionFactory;
public Service(ISessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
void DoSomethingWithChildrenNamedBob(int parentId)
{
using(var session = sessionFactory.OpenSession())
{
var parent = session.Get<Parent>(parentId);
// Will cause lazy fetch of all children!
var childrenNamedBob = parent.Children.Where(c => c.Name == "Bob");
// do something with the children
}
}
}
我知道这不是最好的例子,因为在这种情况下,可能只是直接查询子实体,但我遇到过我已经有一个父对象并且需要遍历它的特定子树的情况。