0

I am new to LINQ and trying to convert an SQL subquery to lINQ. Can we write subqueries like SQL in LINQ?

here is the database

Table EMP                                                                                                  
Name       Null?         Type

EMPNO      NOT NULL      NUMBER(4)
NAME                    VARCHAR2(10)
JOB                     VARCHAR2(9)
MGR                     NUMBER(4)
HIREDATE                DATE
SAL                     NUMBER(7,2)
COMM                    NUMBER(7,2)
DEPTNO                  NUMBER(2)


Table Dpt
Name        Null?        Type
DEPTNO      NOT NULL NUMBER(2)
DNAME                VARCHAR2(14)
LOC                  VARCHAR2(13)

Here is the SQL query

SELECT *
FROM emp
WHERE deptno IN (SELECT deptno
                 FROM dept
                 WHERE dname = 'RESEARCH');

Here is my effort:

var r = (from query in conn.EMPs
         where (query.DEPTNO == (from q in conn.DEPTs 
                                 where q.DNAME == "RESERCH"
                                 select q.DEPTNO)) 
         select new
         {
          query
         }).ToList();
13
  • What's wrong with your effort? Why not use join? Commented Jul 1, 2018 at 12:22
  • You might want to checkout Linqpad Commented Jul 1, 2018 at 12:23
  • I had done this using joins but I am wondering can we do this using subqueries. if yes, then what's the right format because I am getting wrong syntax error while executing this. Commented Jul 1, 2018 at 12:27
  • 1
    where ((from q in conn.DEPTs where q.DNAME == "RESERCH" select q.DEPTNO).Contains(query.DEPTNO)) Commented Jul 1, 2018 at 12:30
  • 1
    Please edit your question. And I mean the classes not the database tables. Commented Jul 2, 2018 at 6:53

2 Answers 2

1

I like using joins :

var r = (from query in conn.EMPs
        join q in conn.DEPTs on query.deptno equals q.DEPTNO 
        select new { query = query, q = q})
        .Where(x => x.q.DNAME == "RESEARCH")
        .ToList();
Sign up to request clarification or add additional context in comments.

Comments

1

var departmentNos = dept.Where(dpt => dpt.dname == 'RESEARCH').Select(dptNo => dptNo.deptno);

var employees = emp.Where(e => departmentNos.Contains(e.deptno));

employees is the final outcome.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.