How to run a subquery in LINQ C #?

1

How to run a subquery in LINQ C #?

SELECT ap.ID
    FROM Aplicativo AP
WHERE AP.Tipo IN (2,6) 
AND AP.ID NOT IN (SELECT filhoID FROM relacoesobjeto WHERE filhoclasse = 555)
    
asked by anonymous 10.04.2018 / 19:11

2 answers

1

It would look something like this, it would help if you had the objects, variables, or part of your code to best contextualize your scenario.

// SELECT filhoID FROM relacoesobjeto WHERE filhoclasse = 555
var listaIds = db.relacoesobjeto.Where(u => u.filhoclasse == 555).ToList();

// Subquery
// SELECT ap.ID FROM Aplicativo AP WHERE AP.Tipo IN (2,6)
var aplicativo = db.Aplicativo
                    .Where(u => u.Tipo == 2 || u.Tipo == 6)
                    .Where(u => !listaIds.Any(p => p.filhoID == u.ID))
                    .ToList();
    
10.04.2018 / 19:15
1

One way to do this is to create a new variable with let where your ids would be, then just use the Contains method to check if id matches the query.

See this example:

var apps = from a in Aplicativo 
            let ids = from r in relacoesobjeto select r.filhoID 
            where ids.Contains(a.ID)
        select a;

See more here .

    
10.04.2018 / 19:22