OR join using Linq

3

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 of the Id column of Table4 . Home I have the following linq:

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 data from Table4 based on the t2 and t3 items, but can not use OR (||) as I have done in the 4th line.

I'm using Entity Framework. Could someone help me?

    
asked by anonymous 14.10.2015 / 13:47

1 answer

1

I made an example using classes to show how linq (with lambda) should be done. You can change && to || if 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; }
}
    
20.10.2015 / 18:19