c# – OR em join usando Linq

Question:

I have the following tables:

Tabela1                Tabela2                               Tabela3                               Tabela4
+----+-----------+     +----+-----------+------+------+      +----+-----------+------+------+      +----+-----------+
| Id | Descricao |     | Id | Descricao | T1Id | T4Id |      | Id | Descricao | T1Id | T4Id |      | Id | Descricao |
+----+-----------+     +----+-----------+------+------+      +----+-----------+------+------+      +----+-----------+
| 1  | Item1     |     | 1  | Item1     |   1  |   1  |      | 1  | Item1     |   2  |   2  |      | 1  | Item1     |
| 2  | Item2     |     | 2  | Item2     |   1  |   2  |      | 2  | Item2     |   2  |   2  |      | 2  | Item2     |
+----+-----------+     | 3  | Item3     |   2  |   2  |      | 3  | Item3     |   1  |   1  |      | 3  | Item3     |
                       +----+-----------+------+------+      +----+-----------+------+------+      +----+-----------+

In both Table2 and Table3 , the T4Id column is a foreign key from the Id column of Table4 .

I have the following link:

from t1 in db.Tabela1
join t2 in db.Tabela2 on t1.Id equals t2.T1Id
join t3 in db.Tabela3 on t1.Id equals t3.T1Id
join t4 in db.Tabela4 on ((t2.T4Id equals t4.TId) || (t3.T4Id equals t4.TId))
where t1.Id == 1
select t4;

I need to get the data from Table4 based on the t2 and t3 items, but I can't OR (||) the way I've been doing in the 4th row.

I am using Entity Framework.

can anybody help me?

Answer:

I made an example using classes to show how linq (with lambda) should be done. You can change the && by || in case you want the result to be in one of the tables, but not necessarily in both.

class Program
{
    static void Main(string[] args)
    {
        var tabela1 = new List<Tabela1>();
        var tabela2 = new List<Tabela2>();
        var tabela3 = new List<Tabela3>();
        var tabela4 = new List<Tabela4>();

        var query = tabela4.Where(x => 
            tabela2.Any(y => y.Tabela4 == x) && 
            tabela3.Any(y => y.Tabela4 == x));
    }
}

public class Tabela1
{
    public int Id { get; set; }
    public string Descricao { get; set; }
}

public class Tabela2
{
    public int Id { get; set; }
    public string Descricao { get; set; }
    public Tabela1 Tabela1 { get; set; }
    public Tabela4 Tabela4 { get; set; }
}

public class Tabela3
{
    public int Id { get; set; }
    public string Descricao { get; set; }
    public Tabela1 Tabela1 { get; set; }
    public Tabela4 Tabela4 { get; set; }
}

public class Tabela4
{
    public int Id { get; set; }
    public string Descricao { get; set; }
}
Scroll to Top