Question

I'm trying to get a result that only returns the parent if the child isn't null. I am new to nhibernate and the QueryOver syntax so sorry if this is completely wrong but i attempted this:

return session.QueryOver<Parent>().Where(x => x.Child != null).SingleOrDefault();

However, this still returns the parent row. I then tried the following:

Child child = null;
return session.QueryOver<Parent>()
.JoinAlias(x => x.Child, () => child)
.Where(() => child.Name != null)
.And(x=>x.Id == id).SingleOrDefault();

Still no luck as i get the parent row anyway. What am i doing wrong? I am pretty sure I am approaching it wrong just can't figure out an alternative.

Was it helpful?

Solution

The base query should be something like this:

Parent parentAlias = null;
Child childAlias = null;

return session.QueryOver<Parent>(() => parentAlias).WithSubquery
      .WhereExists(QueryOver.Of<Child>(() => childAlias)
         .Where(() => parentAlias.Id == childAlias.Parent.Id)
         .Select(c => childAlias.Id))
      .SingleOrDefault();

note the use of aliases, and the fact that I resolved your query by using a subquery. Note even that in a subquery, the "join condition" must be "inserted" manually (I've used parentAlias.Id == childAlias.Parent.Id)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top