2

I am using NHibernate 3.0 and was comparing Query and QueryOver

var p = _prepo.Query<Party>()
            .Where(c => c.Person.LastName == "Bobby")
            .FirstOrDefault();

The above works, I get proxy class for p.Person if I view the object graph.

var p = _prepo.QueryOver<Party>()
            .Where(c => c.Person.LastName == "Bobby")
            .FirstOrDefault();

This one fails with error ==> could not resolve property: Person.LastName of:

Why?

Darius Kucinskas
  • 10,193
  • 12
  • 57
  • 79
user357086
  • 404
  • 1
  • 9
  • 23
  • I'm guessing that you are using the NHibernate.Linq extension. I discovered that the resulting SQL questions is almost exactly the same (at least for this type of question (I would call it a "first order nested query")). `Note:` If the `LastName` had been the primary/foreign key the `QueryOver` would have worked just as it was written. – Markus Mar 07 '14 at 13:55

2 Answers2

6

I'm not familiar with the Linq provider but when using QueryOver you have to use a join to do a query like that:

Example 1

IQueryOver<Cat,Kitten> catQuery =
session.QueryOver<Cat>()
    .JoinQueryOver(c => c.Kittens)
        .Where(k => k.Name == "Tiddles");

Example 2

Cat catAlias = null;
Kitten kittenAlias = null;

IQueryOver<Cat,Cat> catQuery =
    session.QueryOver<Cat>(() => catAlias)
        .JoinAlias(() => catAlias.Kittens, () => kittenAlias)
        .Where(() => catAlias.Age > 5)
        .And(() => kittenAlias.Name == "Tiddles");
Cole W
  • 15,123
  • 6
  • 51
  • 85
0

It works when you use Linq in this case because the filtering is being done on the client, not in the database. So it is actually the IEnumerable version of Where that is running which is not related to NHibernate.

The QueryOver uses Expression<Func<T,object>> which NHibernate tries to translate to SQL but fails. For reasons unknown to me you must explicitly join using JoinQueryOver or JoinAlias.

Some more info on QueryOver here: http://nhibernate.info/blog/2009/12/17/queryover-in-nh-3-0.html

hazzik
  • 13,019
  • 9
  • 47
  • 86
Thomas
  • 2,368
  • 20
  • 22