You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NHibernate查询咨询:关联表时按规则筛选价格的实现

解决NHibernate QueryOver的分支筛选需求

嘿,我来帮你调整这个查询条件!你原来的OR逻辑确实不符合需求——它会同时检查两个价格,不管有没有关联AffiliateProduct。而你要的是分支判断:有关联就用关联产品的价格,没关联就用评论自身的价格。

不用切换到Criteria,QueryOver完全能搞定这个逻辑,你只需要把筛选条件改成下面这样:

ProductReview productReview = null; 
AffiliateProduct affiliateProduct = null;

var queryOver = _session.QueryOver(() => productReview)
    .JoinAlias(x => x.AffiliateProduct, () => affiliateProduct, JoinType.LeftOuterJoin)
    .Where(Restrictions.Disjunction()
        .Add(Restrictions.And(
            Restrictions.IsNotNull(Projections.Property(() => affiliateProduct)),
            Restrictions.Ge(Projections.Property(() => affiliateProduct.Price), 100m)
        ))
        .Add(Restrictions.And(
            Restrictions.IsNull(Projections.Property(() => affiliateProduct)),
            Restrictions.Ge(Projections.Property(() => productReview.Price), 100m)
        ))
    );

如果你的NHibernate版本支持Lambda风格的条件写法,也可以用更简洁的方式:

queryOver = queryOver.Where(() => 
    (affiliateProduct != null && affiliateProduct.Price >= 100m) 
    || (affiliateProduct == null && productReview.Price >= 100m)
);

逻辑说明

  • 第一个条件组:当AffiliateProduct存在(不为null)时,检查它的Price是否≥100
  • 第二个条件组:当AffiliateProduct不存在(为null)时,检查ProductReview自身的Price是否≥100
  • 用Disjunction()(对应SQL的OR)把两组条件组合起来,确保满足其中一种情况即可

这样就能精准匹配你想要的业务逻辑啦!

内容的提问来源于stack exchange,提问作者myozarni23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:45:45