sql - NHibernate QueryOver : Disjuction with restriction in join

标签 sql nhibernate queryover

我想将两个限制进行“或”组合,一项与父级相关,一项与子级相关。

我有以下代码:

var query = Session.QueryOver<Project>()
            .Where(x => x.AccountId == Scope.AccountId)
            .And(x => x.Archived != active)
            .AndRestrictionOn(x => x.Name).IsLike("%" + text + "%")
            .JoinQueryOver(x => x.Customer)
                .WhereRestrictionOn(c => c.Name).IsLike("%" + text + "%")
            .OrderBy(x => x.Id).Desc
            .Fetch(x => x.Customer).Eager;

SQL 输出:

SELECT   this_.Id              as Id2_1_,
         this_.Account_id      as Account2_2_1_,
         this_.Name            as Name2_1_,
         this_.Info            as Info2_1_,
         this_.Archived        as Archived2_1_,
         this_.Customer_id     as Customer6_2_1_,
         customer1_.Id         as Id1_0_,
         customer1_.Account_id as Account2_1_0_,
         customer1_.Name       as Name1_0_
FROM     [Project] this_
         inner join [Customer] customer1_
           on this_.Customer_id = customer1_.Id
WHERE    this_.Account_id = 5 /* @p0 */
         and not (this_.Archived = 1 /* @p1 */)
         and this_.Name like '%dim%' /* @p2 */
         and customer1_.Name like '%dim%' /* @p3 */
ORDER BY customer1_.Id desc

不幸的是,这两个限制之间存在 AND 关系:

this_.Name like '%dim%' and customer1_.Name like '%dim%'

我想要用 OR 代替,如下所示:

this_.Name like '%dim%' or customer1_.Name like '%dim%'

如何使用新的 QueryOver API 解决此查询?

最佳答案

您需要使用别名。

完整的查询应该是:

Customer customerAlias = null;

/* 1st - create base query */
var query = Session.QueryOver<Project>()
            .JoinAlias(x => x.Customer, () => customerAlias)
            .Where(x => x.AccountId == Scope.AccountId)
            .Where(x => x.Archived != active);

/* 2nd - create the disjunction */
var disjunction = new Disjunction();

disjunction.Add(Restrictions.On<Project>(p => p.Name).IsLike(text, MatchMode.Anywhere));
disjunction.Add(Restrictions.On(() => customerAlias.Name).IsLike(text, MatchMode.Anywhere));

/* 3rd - complete query */
query = query.Where(disjunction)                
             .OrderBy(x => x.Id).Desc;

关于sql - NHibernate QueryOver : Disjuction with restriction in join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5201884/

相关文章:

mysql - 为每组仅选择前 2 条记录

nhibernate - 为什么 nhibernate 不附带像 UoW 这样的合适的 session 管理器?

nhibernate - 有关 NHibernate Criteria 查询 groupby 属性的帮助

c# - 如何在 Nhibernate 中对子集合执行 QueryOver

c# - 带表达式树的 nhibernate queryover LIKE

mysql - 在 2 个或更多表上使用列名称作为结果标题

php - 如何使用 DATE_FORMAT() 对表格日期进行排序?

sql - sql "in"语句可以处理的最大变量是多少

c# - 扩展 Nhibernate 以在获取或映射中使用 "inner remote join"

nhibernate - QueryOver<T> 上的析取总是指根实体