Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disjunction on QueryOver<T> always refers to root entity

I'm trying to add a certain numbers of OR conditions using disjunction on X number of entities that implements a certain interface containing date information. My problem is that when the SQL is generated all my disjunction conditions points to the root entity of my QueryOver.

I have created a generic method to add my conditions

    public static QueryOver<T,T2> AddChangedCondition<T,T2>(this QueryOver<T,T2> query, DateTime from, DateTime to, Disjunction disjunction) where T2 : IHaveDate
    {
        if(disjunction == null )
            disjunction = new Disjunction();

        disjunction.Add<T2>(k => (k.DeleteDate > from && k.DeleteDate  < to)
                || k.CreatedDate > from
                || k.UpdatedDate > from);

        return query;
    }

I want to use it like this:

Disjunction disjunction = null;
var query = QueryOver.Of<User>()
    .AddChangedCondition(fromDate,toDate, disjunction)
    .JoinQueryOver<Program>(user => user.Programs)
        .AddChangedCondition(fromDate,toDate, disjunction);

query.Where(disjunction);

Sql generated from this will look something along the lines of

select ....
from User
where
(
    (
        this_.raderadDatum > @p1 
        and this_.raderadDatum < @p2
    ) 
    or this_.skapadDatum > @p3 
    or this_.uppdateradDatum > @p4
    )
or
    (
        this_.raderadDatum > @p1 
        and this_.raderadDatum < @p2
    ) 
    or this_.skapadDatum > @p3 
    or this_.uppdateradDatum > @p4
    )

I've tried different solutions using aliases but no success. Would be greatful for any help!

like image 279
ds99jove Avatar asked Feb 25 '23 16:02

ds99jove


1 Answers

try in this way, I've inserted some random conditions and I used Aliases

 var qOver = _session.QueryOver<User>(() => usr)         
     .JoinAliases(() => usr.Programs, prg, JoinType.LeftOuterJoin)
     .Where(Restrictions.Or(
                Restrictions.On(() => usr.ID).IsIn(MyValue)
                ,Restrictions.Or(
                   Restrictions.On(() => prg.ID).IsIn(MyValue)
                  , Restrictions.On(() => prg.ID).IsNull)
                 )
               )
     .List<User>();

In this way your SQL code will be the following

SELECT ....
FROM User
INNER JOIN Program On (...conditions...)
WHERE User.ID = 'MyValue'
OR (Program.ID IN ('Value1','Value2') OR Program.ID IS NULL)

I hope it's helpful

like image 131
Faber Avatar answered Mar 03 '23 16:03

Faber