【问题标题】:Detached criteria - how to to specify join conditions分离条件 - 如何指定连接条件
【发布时间】:2013-05-17 11:43:40
【问题描述】:

我正在尝试使用 Nhibernate 分离标准从数据库中检索一些数据。问题是我不知道如何在分离条件中指定连接条件。请在下面找到我的代码,

var criteria = DetachedCriteria.For<ExtraRiskQuestionAnswer>("extraRiskQuestionAnswer")
                .CreateAlias("RefRiskQuestion", "refRiskQuestion", JoinType.RightOuterJoin)
                .Add( Restrictions.Disjunction().
                     Add(Restrictions.Eq("CRMContactId", crmContactId))
                     .Add(Restrictions.IsNull("CRMContactId")));

这被翻译成 -

SELECT refriskque1_.RefRiskQuestionId as y0_, refriskque1_.Question as y1_, this_.Answer as y2_ 
FROM FactFind.dbo.TExtraRiskQuestionAnswer this_ 
right outer join Administration.dbo.TRefRiskQuestion refriskque1_ on this_.RefRiskQuestionId=refriskque1_.RefRiskQuestionId 

WHERE this_.CRMContactId = 4670861 or this_.CRMContactId is null

但我想要的是它应该被翻译成下面。

SELECT refriskque1_.RefRiskQuestionId as y0_, refriskque1_.Question as y1_, this_.Answer as y2_ 
FROM FactFind.dbo.TExtraRiskQuestionAnswer this_ 
right outer join Administration.dbo.TRefRiskQuestion refriskque1_ on this_.RefRiskQuestionId=refriskque1_.RefRiskQuestionId 
and this_.CRMContactId = 4670861 or this_.CRMContactId is null

非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: .net sql nhibernate detachedcriteria


    【解决方案1】:

    NHiberante 真的很强大。您使用的方法的重载之一CreateAlias 如下所示:

    public DetachedCriteria CreateAlias(string associationPath
    , string alias
    , JoinType joinType
    , ICriterion withClause);
    

    本例中最有趣的部分是最后一个withClause。这实际上是直接放入 JOIN 子句的条件定义

    所以你应该做的是这样的事情:

    var restriction = Restrictions.Disjunction()
      .Add(Restrictions.Eq("CRMContactId", crmContactId))
      .Add(Restrictions.IsNull("CRMContactId")));
    

    这只是调整 DetachedCriteria 的定义:

    var criteria = DetachedCriteria.For<ExtraRiskQuestionAnswer>("extraRiskQuestionAnswer")
      .CreateAlias("RefRiskQuestion"
      , "refRiskQuestion"
      , JoinType.RightOuterJoin
      , restriction ) // HERE we go, that will be placed where you expected
    

    现在你应该有你需要的了。换句话说,JOIN 子句的任何附加限制都必须放在 WithClause 中 .

    【讨论】:

    • 非常感谢它的工作。但是我们需要在限制中使用 extraRiskQuestionAnswer.CRMContactId,因为它无法解析 CRMContactId。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多