Search code examples
c#nhibernatefluent-nhibernatequeryover

NHibernate QueryOver "select where true"


I need to select the records the for the logged in user or the the records for all users if the logged in user is the manager.

int userId = 1;
bool isManager = true; // or false ;

IQueryOver<Demanda, Demanda> Query1 =
nhibernateSession.QueryOver<Demanda>(() => DemandaAlias)
    .Where(() =>
       (DemandaAlias.userID == userId) ||
       (isManager)
);

That would translate to SQL someting like this:

Select * from Demanda where Demanda.userId=1 or 1=1

How do i white the "constant" parameter ?


Solution

  • The most usual way is to apply an if statement in C#, while building the query.

    var query = nhibernateSession
        .QueryOver<Demanda>(() => DemandaAlias);
    
    var someTestIfShouldApplyThisFilter = ...;
    
    if (someTestIfShouldApplyThisFilter)
    {
        query = query.Where(() => (DemandaAlias.ID == userId);
    }
    

    and later we can consume that reference to get a list (or apply/not apply other where conditions based on other if statements)

    query.List<Demanda>();