1

我正在尝试使用 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

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

4

1 回答 1

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 中。

于 2013-05-17T12:21:18.657 回答