NHibernate Parent Selection Criteria if the child in the collection has a specific value

If I have the following class structure, what are the NHibernate criteria for choosing a parent if one of them has a specific name?

 public class Child
 {
     public int Id { get; set; }
     public int Name { get; set; }
 }

 public class Parent
 {
     public int Id { get; set; }
     public IList<Child> Children { get; set; }
 }
+5
source share
2 answers

I would just create an alias for the collection and add restrictions.

var parentsWithKidName = session.CreateCriteria<Parent>()
    .CreateAlias("Children", "c", JoinType.InnerJoin)
    .Add(Restrictions.Eq("c.Name", childName))
    .SetResultTransformer(Transformers.DistinctRootEntity()) 
    .List<Parent>();

This will lead to

select p.* 
from parent p 
inner join child c on /* however it mapped? */
where c.Name = ?

A separate root entity transformer processes the result set and removes duplicate parents. They still meet the wire though.

+15
source

, , , , .

public virtual IList<T> GetByChildCriteria(string childName,
   params ICriterion[] criterion)
{
     ICriteria criteria = NHibernateSession
     .CreateCriteria(persitentType)
     .CreateCriteria(childName);
     foreach (ICriterion criterium in criterion)
     {
         criteria.Add(criterium);
     }
     return criteria.List<T>();
}

. NHibernateSession ISession.

0

All Articles