使用IQueryOver的NHibernate - 使用子查询和/或条件创建where-condition

时间:2012-07-03 12:24:32

标签: nhibernate subquery criteria queryover icriteria

当我这样做时

Acc accountAlias = null;
var subQuery = QueryOver.Of<Temp>()
               .Where(x=>x.IsAccepted==null)
               .And(x=>x.Account.Id==accountAlias.Id);

var results = session.QueryOver<Acc>(()=>accountAlias)
              .Where(x=>x.User.Id==65)
              .WithSubquery.WhereExists(subQuery);

这将创建以下sql:

select *
from Accounts a
where a.User_Id=65
and exists (
    select t.Account_Id
    from Temporary_Accounts t
    where t.IsAccepted is null and t.Account_Id=a.Account_Id)

如何添加一个或条件,NHibernate将生成以下sql:

select *
from Accounts a
where a.User_Id=65 
and (a.Amount = 100 or exists (
    select t.Account_Id
    from Temporary_Accounts t
    where t.IsAccepted is null and t.Account_Id=a.Account_Id))

1 个答案:

答案 0 :(得分:3)

未经测试,但这样的事情可能会成功

Acc accountAlias = null;
var subQuery = QueryOver.Of<Temp>()
               .Where(x => x.IsAccepted == null)
               .And(x => x.Account.Id == accountAlias.Id);

var results = session.QueryOver<Acc>(()=>accountAlias)
                  .Where(Restrictions.Disjunction()
                     .Add(Subqueries.WhereExists(subQuery))
                     .Add(x => x.Amount == 100))
                  .And(x => x.User.Id = 65)
                  .List();