views:

38

answers:

1

Hi, I have this problem: When I try to implement Ayende's complex searching found at: http://ayende.com/Blog/archive/2006/12/07/ComplexSearchingQueryingWithNHibernate.aspx with the object graph: Person: M:1 Address: M:1 Street: M:1 Place: M:1 Country I get the following error: NHibernate.QueryException: Cannot use subqueries on a criteria without a projection. I am doing this:

public List<Person> Find() 
{ 
    DetachedCriteria query = DetachedCriteria.For<Person>(); 
    AddAddressQuery(query); 
    return personRepository.Find(query);
} 

private void AddAddressQuery(DetachedCriteria query) 
{ 
     DetachedCriteria addressQuery = null; 
     if (!String.IsNullOrEmpty(SearchParams.HouseNumer)) 
     { 
         addresaQuery = DetachedCriteria.For<Address>(); 
         addresaQuery.Add(Restrictions.Eq("HouseNumer", 
SearchParams.HouseNumer)); 
     } 
     this.AddStreetQuery(ref addressQuery); 
     if (addressQuery != null) 
     { 
         query.CreateCriteria("Address1", 
"address1").Add(Subqueries.Exists(addressQuery)); 
     } 
} 

private void AddStreetQuery(ref DetachedCriteria query) 
{ 
    DetachedCriteria streetQuery = null; 
    if (this.SearchParams.StreetId.HasValue) 
    { 
        streetQuery = DetachedCriteria.For<Street>(); 
        streetQuery .Add( Restrictions.Eq("Id", 
this.SearchParams.StreetId.Value)); 
    } 
    if (streetQuery != null) 
    { 
        query = query ?? Query.CreateCriteria("Address1"); 
        query.CreateCriteria("Street", 
"street").Add(Subqueries.Exists(streetQuery )); 
    } 
} 

What Am I doing wrong? Please help

+1  A: 

Just like the error message - you need to set a projection for any subqueries.

Your variable addressQuery, a DetachedCriteria, is used as a subquery, but it doesn't have a projection. The relevant portion of the query, when converted to SQL, would look like this:

... EXISTS(SELECT FROM Address WHERE HouseNumber = @HouseNumber)

... which is invalid SQL because no columns (a.k.a projections) have been specified in the select clause.

Use SetProjection to specify the columns.

cbp
Is there a way I can see the generated sql from the criteria without executing the criteria?
Luka
@Luka haha, I asked that same question just earlier today :) http://stackoverflow.com/questions/3562839/nhibernate-retrieve-sql-to-be-executed-as-a-string I don't think so.
cbp
lol, I know it is possible with interceptors but I don't want to execute the criteria.
Luka