【问题标题】:NHibernate.QueryException : duplicate association pathNHibernate.QueryException:重复的关联路径
【发布时间】:2011-12-20 07:54:06
【问题描述】:

下面的代码片段描述了我想要使用查询执行的操作,但它因上述错误而崩溃。

Buildings 和 AttributeValues 之间存在一对多的关系,我的目标是找到所有具有 AttributeValue"Large"AttributeValue"Blue" 的建筑物。

        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'

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

【问题讨论】:

  • 这里有类似的问题:Duplicate Association 希望它有所帮助 - 无法在工作中测试它。
  • 仅供参考,我已经设法使用 HQL 创建了一个等效的工作查询,但如果可能的话,我希望不必将基于动态条件的查询转移到 HQL。
  • 感谢您的建议 - 他们似乎得出了相同的结论,即无法使用 Criteria 完成,但鉴于它是一个如此简单的查询,这似乎令人惊讶。

标签: c# nhibernate 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")

【讨论】:

  • 感谢 Pieter 的回复。我们确实查看了子查询,但无法弄清楚如何通过将外部查询中的 id 传递给内部查询来模拟子查询中连接的 on 子句,使用标准。最后,我们使用了 HQL,这使我们能够灵活地进行多个连接。
  • Neil,您可以通过将别名与外部查询相关联来做到这一点。您可以在内部查询中使用该别名并使用 Expression.EqProperty 来比较 Id 值。
猜你喜欢
  • 1970-01-01
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-15
相关资源
最近更新 更多