How to make "OR" between Subquerys using LINQ C#

Asked

Viewed 226 times

4

I would like to implement with LINQ C# (Using Nhibernate as ORM), the following query:

return (from t1 in Session.Query<Tabela1>()
        join t2 in Session.Query<Tabela2>()
        on t1 equals t2.T1
        where (from t3 in Session.Query<Tabela3>()
               where
               t3.Tabela == 1 && t3.Atualizacao >= dataAtualizacao
               select t3.Chave).Contains(t1.Id)
        /* aqui teria que ser um 'or' (||) ao invés de um 'and' (&&), como é feito por default */
        where (from t3 in Session.Query<Tabela3>()
               where
               t3.Tabela == 2 && t3.Atualizacao >= dataAtualizacao
               select t3.Chave).Contains(t2.Id)
        select t1).Distinct().ToList();

To query equivalent in SQL that I want to generate would be similar to:

SELECT * FROM TABELA1 T1
LEFT OUTER JOIN TABELA2 AS T2 ON T2.T1 = T1.ID
WHERE 
(T1.ID IN (SELECT T3.CHAVE FROM TABELA3 
WHERE T3.CODIGOTABELA = 1 AND T3.ATUALIZACAO >= '10/25/2000 13:05:00')
OR /* Esse OR é que não consigo implementar com LINQ, da maneira que está a expressão LINQ nessa linha gera um AND */
T2.ID IN (SELECT T3.CHAVE FROM TABELA3 
WHERE T3.CODIGOTABELA = 2 AND T3.ATUALIZACAO >= '10/25/2000 13:05:00'))

The problem is I haven’t found any way to make the expression "OR" between the 2 subquerys, and by default in LINQ the generated expression is a "AND". Is there any way to make the expression "OR", between the two subquerys?

Note: Could also use Lambda Expressions, instead of LINQ.

  • 1

    Lambda Expression is a way to use LINQ. http://answall.com/questions/14212/diferencas-entre-forma-declarativa-e-imperativa-do-linq/15142#15142

1 answer

4


A chain of wheres is a AND. If you want a OR, puts a OR:

return (from t1 in Session.Query<Tabela1>()
        join t2 in Session.Query<Tabela2>()
        on t1 equals t2.T1
        where (from t3 in Session.Query<Tabela3>()
               where
               t3.Tabela == 1 && t3.Atualizacao >= dataAtualizacao
               select t3.Chave).Contains(t1.Id)
        || (from t3 in Session.Query<Tabela3>()
               where
               t3.Tabela == 2 && t3.Atualizacao >= dataAtualizacao
               select t3.Chave).Contains(t2.Id)
        select t1).Distinct().ToList();
  • Perfect, since I didn’t think of it that way, I had tried || where, where ||, I just didn’t think without the where, knew that there should be a simple way (but not so much). Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.