Yaplex
Yaplex

Reputation: 2284

NHibernate return all parents with child have condition

I have a parent and child classes

class Parent
{
 bool Enable;
List<Child> Children;
}
class Child
{
bool Enable;
}

I want to return all parent where Enable=true and that parent should contain all child where Enable = true.

I created the following

    var parents = Session.QueryOver<Parent>().Where(p => p.Enabled)
        .JoinQueryOver<Child>(p => p.Children).Where(c=>c.Enabled)
        .List<Parent>();

It returns me correct parents (all where Enable=true), but it return all childs (even if enable =false)

Can somebody help me to correct my query?

Upvotes: 1

Views: 676

Answers (1)

Ivo
Ivo

Reputation: 8352

You should return the children where Enable=true and join their parents. Then, you can group them by parent using linq.

Something like this:

var children = Session.QueryOver<Child>(c => c.Children)
                      .Where(c => c.Enabled && c.Parent.Enabled)
                      .Fetch(c => c.Parent) //This will include the parents in the query so you
                      .List<Child>();       //avoid a Select N+1

var childrenByParent = children.GroupBy(x => x.Parent);

Upvotes: 1

Related Questions