Join with three or more lambda tables

Asked

Viewed 13,850 times

6

I made this expression using Lambda and 2 tables.

var resultado = db.T_TarefaParceiro.Join(
                db.T_OsParceiro,
                t1 => t1.IDTarefaParceiro,
                t2 => t2.IDTarefaParceiro,
                (t1, t2) => new { t1, t2 })
                .Where(a => a.t1.IDTarefaParceiro == a.t2.IDTarefaParceiro && a.t2.Is_Tarefa_Fechada == true)
                .Select(i => new { i.t1.CNPJ });

I’m having difficulty placing a third or fourth table. I tried to create another Join clause, but it was a mistake. How I do?

  • I added an example just below, if you want something specific of your models inform equal drawing below, I write the lambda Xpression of it, but, by example can be taken out the logic!

1 answer

9


Everything will depend on how are your relationships and keys, a basic example would be like this:

Tables and relationships

Uma Pessoa pode ter ou não vários Telefones e um Telefone possui um Tipo

inserir a descrição da imagem aqui

Lambda Expression with 2 Join, ie three tables, consequently three models:

using (GenericsContext db = new GenericsContext())
{
    var resultado = db.Pessoas
        .Join(db.Telefones, pessoa => pessoa.PessoaId, telefone => telefone.PessoaId, (pessoa, telefone) => new { pessoa, telefone })
        .Join(db.Tipos, telefone => telefone.telefone.TipoId, tipo => tipo.TipoId, (telefone, tipo) => new { telefone, tipo })
        .Select(x => new
        {                        
            x.telefone.pessoa.PessoaId,
            x.telefone.pessoa.Nome,
            x.tipo.Descricao,
            x.telefone.telefone.Ddd,
            x.telefone.telefone.Numero
        });

    var resultadoToList = resultado.ToList();
}

SQL generated by this expression:

SELECT 
    [Extent1].[PessoaId] AS [PessoaId], 
    [Extent1].[Nome] AS [Nome], 
    [Extent3].[Descricao] AS [Descricao], 
    [Extent2].[Ddd] AS [Ddd], 
    [Extent2].[Numero] AS [Numero]
    FROM   [dbo].[Pessoas] AS [Extent1]
    INNER JOIN [dbo].[Telefones] AS [Extent2] ON [Extent1].[PessoaId] = [Extent2].[PessoaId]
    INNER JOIN [dbo].[Tipos] AS [Extent3] ON [Extent2].[TipoId] = [Extent3].[TipoId]
  • 1

    I understood my mistake. When I create the lambda variable for the third table, I have to call it and then the other variable I’m going to join and then the field. When I put the third and called J1 and when I looked at intellisence, the option was t1 and t2 and I thought that was wrong. It lacked knowledge, of course, and that’s what I’m looking for here. Thank you Harry.

  • No reason, I’m glad you understood and were helpful

Browser other questions tagged

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