Jack Mills
Jack Mills

Reputation: 6132

Fluent Nhibernate QueryOver and Joins

I'm in the process of learning Fluent nHibernate. I'm having trouble with building a query thats not quite the same as the classic examples I've found online. Typically I've found this example:

IQueryOver<Cat,Cat> catQuery =
    session.QueryOver<Cat>(() => catAlias)
        .JoinAlias(() => catAlias.Kittens, () => kittenAlias)
        .Where(() => catAlias.Age > 5)
        .And(() => kittenAlias.Name == "Tiddles");

So from what I understand in this example a Cat object is being returned after being joined on Kittens and then filtered using the kittens name and the cat's age. And the join works because the Cat object has a property called Kittens.

An example of what I'm trying to do would look like this:

Forest f = null;
Tree t = null;

ForestsFound = session.QueryOver<Forest>(() => f)
                    .JoinAlias(() => t.Forest, () => f)
                    .Where(() => t.NumberOfTrees > 1000)
                    .List<Forest>()
                    .ToList<Forest>();

A forest is essentially a lookup table, it's the Tree that has a link to what forest the tree is in but I want to return a distinct list of forests. So in regular sql it would look like:

select f.*
from Forest f
   inner join Tree t
      on t.Forest_id = f.ID
where t.NumberOfTrees > 1000

Upvotes: 1

Views: 6469

Answers (1)

Martin Ernst
Martin Ernst

Reputation: 5679

If you have a relationship from Forest -> Trees then you can do this:

Forest f = null;
Tree t = null;

ForestsFound = session.QueryOver<Forest>(() => f)
    .JoinAlias(() => f.Trees, () => t)
    .Where(() => t.NumberOfTrees > 1000)
    .List<Forest>();

Upvotes: 2

Related Questions