2011-11-02 60 views
4

下面的代码片段描述了我想要使用查询做什么,但它爆炸与上述错误。NHibernate.QueryException:重复的关联路径

有建筑物和AttributeValues之间的1对多的关系,我的目的是要找到具有的"Large"一个AttributeValue"Blue"一个AttributeValue所有建筑物。

 var attributeValueAlias1 = new AttributeValue(); 
     var attributeValueAlias2 = new AttributeValue(); 

     var result = repository 
      .CreateCriteriaFor<Buildings>() 
      .Join(o=>o.AttributeValues,()=> attributeValueAlias1) 
      .Join(o=>o.AttributeValues,()=> attributeValueAlias2) 
      .Add(() => attributeValueAlias1.Value == "Large") 
      .Add(() => attributeValueAlias2.Value == "Blue") 
      .List(); 

有几个帖子在那里,但没有一个解决问题的描述herehere

我可以做这么一个成员资格测试使用criteria.GetCriteriaByAlias(alias)增加,因此不会出现重复的别名错误,但那么只有一个连接添加别名之前,它导致SQL where子句,这将永远是真实的

SELECT * 
FROM Buildings this_ 
    inner join AttributeValues attributev1_ 
    on this_.Id = attributev1_.BuildingId 
WHERE 
    attributev1_.Value = 'Large' 
    and attributev1_.Value = 'Blue' 

这不是一个复杂或不寻常的查询,所以如果没有解决方法,我会感到惊讶。

+0

只是为了信息,我已经成功地创建使用HQL等效工作查询 但不希望有将我们的动态标准,如果可能的话 根据查询到HQL。 –

+0

类似的问题在这里:[重复协会](http://stackoverflow.com/questions/3881286/i-am-getting-a-duplicate-association-path-error-in-the-nhibernate-criteria-whe)希望它帮助 - 无法在工作中测试它。 – matt

+0

感谢您的建议 - 他们似乎得出了相同的结论,它不能用Criteria完成,但它似乎令人惊讶,因为它是这样一个简单的查询。 –

回答

1

您不应该使用连接来做到这一点,正如您可能从异常中猜到的那样。您应该使用两个子查询来测试集合中的值“Blue”和“Large”。我对ICriteria并不擅长,但是生成的SQL应该看起来像这样,我认为这可以在ICriteria中使用(使用Subqueries.PropertyIn)。

select * from Buildings b 
inner join AttributeValues av on b.Id = av.BuildingId 
where av.Id in (select Id from AttributeValues av2 where av2.BuildingId=b.BuildingId and av2.Value="Large") 
and av.Id in (select Id from AttributeValues av3 where av3.BuildingId=b.BuildingId and av3.Value="Blue") 
+0

感谢Pieter.We回顾了子查询,但无法弄清楚如何通过使用标准将外部查询中的id传递给内部查询来模拟子查询中连接的on子句。最后,我们使用了HQL,这使我们可以灵活地进行多个连接。 –

+0

尼尔,你可以通过将别名与外部查询关联来实现。您可以在内部查询中使用该别名,并使用“Expression.EqProperty”来比较Id值。 – Pieter