Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate Criteria Collection Contains

Tags:

nhibernate

I have a parent/child relationship mapped with a many-to-many set.

public class Parent
{
    public ISet<Child> Children { get; set; }
}

public class Child {}

public class ParentMap : ClassMap<Parent>
{
    HasManyToMany(x => x.Children)
        .AsSet();
}

How can I write a query to select all of the parents that contain a given child? I would have guessed that it would be something like this, but this API does not exist:

Session.CreateCriteria<Parent>()
   .Add(Expression.Contains("Children", child)
   .List<Parent>();

I can't for the life of me find the answer anywhere. My brain is not fully functioning today and Google has so far failed me.

like image 277
Stefan Moser Avatar asked Aug 25 '09 18:08

Stefan Moser


People also ask

What is bag in NHibernate?

A bag is an unordered, unindexed collection which may contain the same element multiple times. The . NET collections framework lacks an IBag interface, hence you have to emulate it with an IList. NHibernate lets you map properties of type IList or ICollection with the <bag> element.

What is DetachedCriteria in NHibernate?

The DetachedCriteria class lets you create a query outside the scope of a session, and then later execute it using some arbitrary ISession. A DetachedCriteria may also be used to express a sub-query.


1 Answers

How about something like this?

Session.CreateCriteria<Parent>()
   .CreateCriteria("Children")
   .Add(Expression.Eq("Id", child.Id)
   .List<Parent>();

or

Session.CreateCriteria<Parent>()
   .CreateCriteria("Children")
   .Add(Expression.In("Id", child.Id)
   .List<Parent>();

so you can pass in an array of Ids.

like image 197
RKitson Avatar answered Oct 02 '22 12:10

RKitson