Orange Kid
Orange Kid

Reputation: 544

Find all NHibernate parent entities where HasMany child entity meets criteria

Using Nhibernate and Fluent NHibernate for the mapping, I have a parent entity with a one to many relationship to a child entity.

In the parent entity, I can list all children attached in the

this.HasMany<Child>(x => x.Child).KeyColumn("ParentID").Cascade.None();

The child entity has a begin and end date property. I would like to select all parents who have children where Child.BeginDate >= DateTime.Now && Child.EndDate < DateTime.Now.

I've been banging my head against ways to accomplish this using NHibernate.

This clearly didn't work but my first attempt was this;

s.CreateCriteria<Parent>()
    .Add(Expression.Where<Parent>(x => x.Children.Where<Child>(y => y.BeginDate <= DateTime.Now && y.EndDate > DateTime.Now).Count() > 0))
    .List<Parent>();

I could accomplish with T-SQL like so;

SELECT p.* FROM dbo.ParentTable p
WHERE (SELECT COUNT(*) FROM dbo.ChildTable c WHERE p.ID = c.ParentID AND c.BeginDate <= GETDATE() AND c.EndDate > GETDATE()) > 0

Success!

s.CreateCriteria<Parent>()
    .CreateAlias("Child", "Child")
    .Add(Restrictions.Le("Child.BeginDate", DateTime.Now))
    .Add(Restrictions.Gt("Child.EndDate", DateTime.Now))
    .SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer())
    .List<Parent>();

Upvotes: 1

Views: 1955

Answers (1)

Denis Ivin
Denis Ivin

Reputation: 5644

See if this works for you:

var criteria = Session.QueryOver<Parent>();
criteria.JoinQueryOver<Child>(x => x.Children)
        .Where(y => (y.BeginDate <= DateTime.Now) && (y.EndDate > DateTime.Now));

criteria.TransformUsing(Transformers.DistinctRootEntity);
return criteria.List();

Upvotes: 2

Related Questions