Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nHibernate Criteria for selecting a parent if a child in a collection has a specific value

If I have the following class structure what is the NHibernate criteria to select a parent if one of it's children 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; }
 }
like image 860
AwkwardCoder Avatar asked Apr 28 '10 13:04

AwkwardCoder


1 Answers

I'd just create an alias to 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 would result in

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

The distinct root entity transformer will process the result set and remove duplicated parents. They still come across the wire though.

like image 75
dotjoe Avatar answered Sep 28 '22 04:09

dotjoe