Daniel Williams
Daniel Williams

Reputation: 9304

How to select parent and only one child, based on a property?

In Fluent NHibernate, I have a class A, with an IList of children B.

I want to select all A's which have a child B with a certain property B=="foo"

I do not want to get back any other children of A.

What is the Query expression to get this?

var list = session.Query<A>()
  .FetchMany(a=>a.B)
  .Where( a=>childBs.Any(b=>b=="foo"));

But that returns all of the child Bs, not just the "foo" one.

Upvotes: 0

Views: 199

Answers (2)

Martin Ernst
Martin Ernst

Reputation: 5679

There are some ugly hacks to get it to do what you want (using filters on the collection), but I wouldn't recommend it. Why don't you reverse the query and do:

var list = session.QueryOver<B>()
             .Where(b => b.B == "foo")
             .Fetch(b => b.A).Eager
             .List();

It won't do exactly what you want (if you access b.A.ChildBs it will load that collection), but it will retrieve the data you're looking for (assuming you have a relationship from B to A)

Upvotes: 1

Diego Mijelshon
Diego Mijelshon

Reputation: 52725

NHibernate will never retrieve a half-loaded collection.

If you want to retrieve one A with one B, use a projection.

Upvotes: 0

Related Questions