Search code examples
c#nhibernateicriteria

NHibernate ICriteria Restriction find properties in a collection that match a value


Suppose I have the following:

public class MyClass 
{
   public List<Widget> WidgetList { get; set; }
}

public class Widget 
{
   public string Foo { get; set; }
   public string Bar { get; set; }
}

I want to query this using the NHibernate ICriteria API to find all MyClass that contain a Widget where any Bar has a certain value. I can use Restrictions.Into find a property that is in a list of values, but I can't figure out how to reverse this and find out if a collection property contains something matching a value.

I'm trying to achieve something like:

criteria = criteria.Add(Restrictions.Eq("WidgetList.Bar", myValue));

(where the above is obviously incorrect)

How can I do this?


Solution

  • I achieved what I wanted by creating an alias:

    criteria.CreateAlias("WidgetList", "widgets", JoinType.LeftOuterJoin);
    criteria = criteria.Add(Restrictions.Eq("widgets.Bar", myValue));