无法解析属性(复杂属性)

时间:2012-07-08 20:40:53

标签: linq nhibernate queryover

我有一个带有NHibernate的asp.net mvc应用程序,我不知道如何解决查询某些数据的问题。我有这个问题:

// 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);

当我尝试执行此查询时,我收到此消息的异常: “无法解析属性:Equipament.Company.Id of:DomainModel.Laudo

我该怎么做才能解决这个问题? 感谢

2 个答案:

答案 0 :(得分:2)

您不能使用其他类似的实体属性。 NHibernate期望表达式可以被评估为当前实体的属性。您需要使用JoinQueryOverJoinAlias加入其他实体,然后执行where

使用JoinQueryOver

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

使用JoinAlias

Equipment equipment = null;
Company company = null;

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

更多信息:
What is the difference between JoinQueryOver and JoinAlias?
What can be used as a NHibernate QueryOver alias?
Complex nHibernate QueryOver expression

答案 1 :(得分:1)

为您的问题选择的标签让我觉得您不想使用QueryOver,而是使用LINQ。

这是通过在Query命名空间中使用扩展方法NHibernate.Linq来实现的:

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);