2

I have a asp.net mvc application with NHibernate and I do not know how to resolve a problem to query some data. I have this query:

// create query
var query = session.QueryOVer<Laudo>().Fetch(x => x.Equipament).Eager;

// add some filters
if (idEquipament.HasValue) 
  query = query.And(x => x.Equipament.Id == idEquipament.Value);

//I got the error here...
if (idCompany.HasValue)
  query = query.And(x => x.Equipament.Company.Id == idCompany.Value);

When I try to execute this query, I've got an exception with this message: "could not resolve property: Equipament.Company.Id of: DomainModel.Laudo"

what can I do to fix this problem? Thanks

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194

2 Answers2

2

You cannot use another entity property like that. NHibernate expects expression that can be evaluated to property of the current entity. You need to use JoinQueryOver or JoinAlias to join another entity, and perform where after that.

With JoinQueryOver:

// ...
query = query.JoinQueryOver(x => x.Equipment)
    .JoinQueryOver(x => x.Company)
    .Where(c => c.Id == idCompany.Value);

With JoinAlias:

Equipment equipment = null;
Company company = null;

// ...
query = query.JoinAlias(x => x.Equipment, () => equipment)
    .JoinAlias(() => equipment.Company, () => company)
    .Where(() => company.Id == idCompany.Value);

Some more info:
What is the difference between JoinQueryOver and JoinAlias?
What can be used as a NHibernate QueryOver alias?
Complex nHibernate QueryOver expression

Community
  • 1
  • 1
Miroslav Popovic
  • 12,100
  • 2
  • 35
  • 47
  • just one question, is there any way to fill only some properties of this join, I mean... Company entity has more than 20 fields, and I need just 2 (Id and Name), is there any way to do that? Thanks – Felipe Oriani Jul 08 '12 at 22:29
  • Projections? http://www.nhforge.org/doc/nh/en/index.html#queryqueryover-projections – Miroslav Popovic Jul 08 '12 at 22:33
1

The tags chosen for your question make me think you didn't want to use QueryOver, but LINQ.

This is achieved by using the extension method Query, in the NHibernate.Linq namespace:

var query = session.Query<Laudo>().Fetch(x => x.Equipament);
if (idEquipament.HasValue) 
  query = query.Where(x => x.Equipament.Id == idEquipament.Value);
if (idCompany.HasValue)
  query = query.Where(x => x.Equipament.Company.Id == idCompany.Value);
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • Hi @Diego, nice tip, but I used AND() method because It genarates an AND operator on the sql statment between the parameters (I have more parameters on my original method) something like `idEquipament = ? AND Equipament.Company_Id = ?` ... and using like you said, is there any advantage or it will be the same? Thank you! – Felipe Oriani Jul 09 '12 at 02:37