How to run a subconsultation on LINQ C#?

Asked

Viewed 112 times

1

How to run a subconsultation on 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)

2 answers

1


It would be something similar to this, it would help if you had the objects, variables or part of your code to better contextualize in 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();
  • Thank you Diego Vieura.. That’s what I wanted! It worked perfectly.

  • @Brunosouza Glad I could help! :)

1

One way to do this is by creating a new variable with the let where their ids would be, then just use the method Contains to check whether the id corresponds in consultation.

Take 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.

  • downvoter there is something I can improve on the answer?

Browser other questions tagged

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