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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With