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

4

2 回答 2

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

于 2012-07-08T21:11:41.600 回答
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);
于 2012-07-09T00:38:38.030 回答