nhibernatesubquerycriteriaqueryovericriteria

NHibernate with IQueryOver - create where-condition with subquery and or condition


When I do

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);

this will create the fallowing 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)

How can I add a or condition, that NHibernate will generate the fallowing 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))

Solution

  • Not tested but something like tihs may do the trick

    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();