Convert SQL to LINQ C#

Asked

Viewed 78 times

1

how do I convert the last line of this SQL to LINQ?

SELECT* FROM
                 ACOMPANHAMENTO A,
                 PRESOS_ACOMPANHAMENTO PA, 
                 PRESOSS P
             WHERE
                 P.ID_PRESOS = 300 AND
                 PA.ID_PRESOS = P.ID_PRESOS AND
                 A.ID_Acomp = PA.ID_Acomp AND
                 A.ID_Area_Acomp = 15 AND
                 A.ID_Sit_Acomp IN (SELECT SA.ID_Sit_Acomp FROM SITUACAO_ACOMPANHAMENTO SA WHERE SA.ST_Sit_Acomp = 'A')

The code below presents my attempt to convert SQL code to LINQ.

var resultado = (from a in contexto.ACOMPANHAMENTOes
                         from pa in contexto.PRESO_ACOMPANHAMENTO
                         from p in contexto.PRESOS
                         where p.ID_Preso == 300 &&
                                  pa.ID_Preso == p.ID_Preso &&
                                  a.ID_Acomp == pa.ID_Acomp &&
                                  a.ID_Area_Acomp == 15 && 
                                  a.ID_Sit_Acomp.ToString().Contains(from sa in contexto.SITUACAO_ACOMPANHAMENTO where sa.ST_Sit_Acomp == "A" select sa.ID_Sit_Acomp)
                         select a).ToList();

2 answers

2


The conversion may be as follows::

var sitAcomp = (from a in SITUACAO_ACOMPANHAMENTO 
                where a.ST_Sit_Acomp == 'A'
                select a).ToList();

var resultado = (from a in contexto.ACOMPANHAMENTOes
                 from pa in contexto.PRESO_ACOMPANHAMENTO
                 from p in contexto.PRESOS
                 where p.ID_Preso == 300 &&
                       pa.ID_Preso == p.ID_Preso &&
                       a.ID_Acomp == pa.ID_Acomp &&
                       a.ID_Area_Acomp == 15 &&
                           (from sa in sitAcomp
                            select sa.ID_Sit_Acomp)
                            .Contains(a.ID_Sit_Acomp)
                 select a).ToList();

1

Another way would be

var resultado = (from a in contexto.ACOMPANHAMENTOes
                 from pa in contexto.PRESO_ACOMPANHAMENTO
                 from p in contexto.PRESOS
                 where p.ID_Preso == 300 &&
                       pa.ID_Preso == p.ID_Preso &&
                       a.ID_Acomp == pa.ID_Acomp &&
                       a.ID_Area_Acomp == 15 &&
                       a.SITUACAO_ACOMPANHAMENTOes.Any(b=>b.ST_Sit_Acomp.Equals("A"))                           
                 select a).ToList();

Browser other questions tagged

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